local _, ZLAUTO = ...

local ZL = ZLAUTO.mainFrame
local background = ZL.background
local ScrollFrame_OnMouseWheel = ZL.ScrollFrame_OnMouseWheel
local btnDelay = ZL.btnDelay
local PlayerIsML = ZL.PlayerIsML
local Prefix = ZL.Prefix
local CountDown = ZL.CountDown
local CreateButton = ZL.CreateButton
local pruneCrossRealm = ZL.pruneCrossRealm
local GetAuctioningCount = ZL.GetAuctioningCount
local GetStartAndIncrementBid = ZL.GetStartAndIncrementBid
local ItemAuctionFrameIsShown = ZL.ItemAuctionFrameIsShown
local tableSort = ZL.tableSort
local emptytable = ZL.emptytable
local pad_left = ZL.pad_left
local GameTooltipShow = ZL.GameTooltipShow
local autoBid = ZL.autoBid
local ConvertSecondsToTime = ZL.ConvertSecondsToTime
local CreateMenu = ZL.CreateMenu
local GetCurrentRoster = ZL.GetCurrentRoster
local IsNeedMail = ZL.IsNeedMail

local cGetItemInfo, cGetItemIcon
if WOW_PROJECT_ID == 1 then
    cGetItemInfo = C_Item.GetItemInfo
    cGetItemIcon = C_Item.GetItemIconByID
else --WOW_PROJECT_ID == 11 then
    cGetItemInfo = GetItemInfo
    cGetItemIcon = GetItemIcon
end

--创建拍卖主窗口
function ZL:CreateAuctionFrame()
    ZL.AuctionFrame = CreateFrame("Frame", "ZLAuctionFrame", ZL, "UIPanelDialogTemplate")
    local AuctionFrame = ZL.AuctionFrame
    AuctionFrame.tableId = 1 --设置默认按钮ID
    AuctionFrame:SetSize(305, 350)
    AuctionFrame:SetPoint("TOPRIGHT", Minimap, "BOTTOMRIGHT", 0, -20)
    AuctionFrame:SetFrameStrata("HIGH")
    AuctionFrame:SetClampedToScreen(true)  --不能超出游戏屏幕，false可以超出游戏屏幕
    AuctionFrame:SetMovable(true)
    AuctionFrame:SetHitRectInsets(0, 0, 0, ZLAuctionFrameDialogBG:GetHeight()+3) --设置鼠标可点击区域
    AuctionFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
    end)
    AuctionFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    AuctionFrame:SetScript("OnShow", function (self)
        self:Update()
    end)
    AuctionFrame.Title:SetText("拍卖清单")
    if WOW_PROJECT_ID ~= 1 then
        _G["ZLAuctionFrameClose"]:ClearAllPoints()
        _G["ZLAuctionFrameClose"]:SetPoint("TOPRIGHT", AuctionFrame, "TOPRIGHT", 2, 1)
    end
    _G["ZLAuctionFrameClose"]:SetScript("OnClick", function ()
        AuctionFrame:Hide()
        -- for _, f in ipairs(AuctionFrame.entries) do
        --     f.Frame1.timer:SetHideCountdownNumbers(true)
        -- end
        ZL.maxFrame:Show()
    end)

    AuctionFrame.settingBtn = CreateFrame("Button", nil, AuctionFrame, "UIPanelButtonTemplate") --, "UIPanelButtonTemplate"
    local settingBtn = AuctionFrame.settingBtn
    settingBtn:SetPoint("LEFT", ZLAuctionFrameTitleBG, "LEFT", 5, 0)
    settingBtn:SetSize(10, 10)
    settingBtn:SetNormalTexture("Interface\\Buttons\\UI-OptionsButton.blp")
    settingBtn:SetScript("OnClick", function ()
        LibStub("AceConfigDialog-3.0"):Open("金团自动拍卖助手")
    end)
    settingBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("点击打开设置窗口", 1, 1, 1)
        GameTooltip:Show()
    end)
    settingBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    AuctionFrame.AllMinBtn = CreateButton(nil, AuctionFrame, "全部折叠", "TOPLEFT", ZLAuctionFrameDialogBG, "TOPLEFT", 2, -5, 80)
    AuctionFrame.AllMinBtn:SetScript("OnClick", function ()
        if AuctionFrame.AllMinBtn:GetText() == "全部折叠" then
            for _, frame in ipairs(AuctionFrame.entries) do
                if frame:IsShown() and frame.Frame1:IsShown() then
                    frame.titleBtn:Click()
                end
            end
            AuctionFrame.AllMinBtn:SetText("全部展开")
        else
            for _, frame in ipairs(AuctionFrame.entries) do
                if frame:IsShown() and (not frame.Frame1:IsShown()) then
                    frame.titleBtn:Click()
                end
            end
            AuctionFrame.AllMinBtn:SetText("全部折叠")
        end
        AuctionFrame:Update()
    end)
    AuctionFrame.histroy= CreateButton(nil, AuctionFrame, "历史", "LEFT", AuctionFrame.AllMinBtn, "RIGHT", 0, 0, 40)
    AuctionFrame.histroy:SetScript("OnClick", function (self)
        ZL.AuctionRecordFrame:Show()
        _G["AuctionRecordFrameTab1"]:Click()
    end)
    AuctionFrame.histroy:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "RIGHT", "LEFT", -8, 0)
        if next(ZL_HISTORY, nil) then
            GameTooltip:AddLine("历史拍卖记录：")
            GameTooltip:AddDoubleLine("名称", "收入                           创建时间")
            for _, data in ipairs(ZL_HISTORY) do
                GameTooltip:AddDoubleLine(data.name, data.totalincome .. "|cffffd100g|r    " .. data.auctiondate, 1, 1, 1, 1, 1, 1)
            end
        else
            GameTooltip:AddLine("没有历史记录！")
        end
        GameTooltip:Show()
    end)
    AuctionFrame.histroy:SetScript("OnLeave", function (self) GameTooltip:Hide() end)
    AuctionFrame.current= CreateButton(nil, AuctionFrame, "当前", "LEFT", AuctionFrame.histroy, "RIGHT", 0, 0, 40)
    AuctionFrame.current:SetScript("OnClick", function (self)
        ZL.GetRemainingTradeTime()
        ZL.AuctionRecordFrame:Show()
        _G["AuctionRecordFrameTab2"]:Click()
    end)
    AuctionFrame.current:SetScript("OnEnter", function (self)
        GameTooltipShow(AuctionFrame.histroy, "RIGHT", "LEFT", -8, 0)
        if ZL_CURRENT.IncomeList and next(ZL_CURRENT.IncomeList, nil) then
            local totalincome = 0
            local totalpayout = 0
            GameTooltip:AddLine("当前收入记录：")
            GameTooltip:AddDoubleLine("名称", "玩家(金额)")
            for _, data in ipairs(ZL_CURRENT.IncomeList) do
                if data.amount > 0 then
                    totalincome = totalincome + data.amount
                else
                    totalpayout = totalpayout + data.amount
                end
                local itemId = string.match(data.notes, "|c........|Hitem:(%d+):")
                if itemId then
                    GameTooltip:AddDoubleLine(
                        "|T" .. cGetItemIcon(data.notes) .. ":12|t " .. data.notes,
                        data.player .. "(" .. data.amount .. ")|cffffd100g|r", 1, 1, 1, 1, 1, 1)
                else
                    GameTooltip:AddDoubleLine(
                        "|T:12|t " .. data.notes,
                        data.player .. "(" .. data.amount .. ")|cffffd100g|r", 1, 1, 1, 1, 1, 1)
                end
            end
            GameTooltip:AddLine("\n总收入：|cffffd100" .. totalincome .. "|rg", 1, 1, 1)
            GameTooltip:AddLine("总支出：|cffffd100" .. (totalpayout == 0 and 0 or -totalpayout) .. "|rg", 1, 1, 1)
            GameTooltip:AddLine("净收入：|cffffd100" .. (totalincome + totalpayout) .. "|rg", 1, 1, 1)
        else
            GameTooltip:AddLine("当前没有收入记录！")
        end
        GameTooltip:Show()
    end)
    AuctionFrame.current:SetScript("OnLeave", function () GameTooltip:Hide() end)
    AuctionFrame.MLFrame = CreateFrame("Frame", nil, AuctionFrame)
    local MLFrame = AuctionFrame.MLFrame
    MLFrame:SetPoint("TOPLEFT", ZLAuctionFrameDialogBG, "TOPLEFT")
    MLFrame:SetWidth(ZLAuctionFrameDialogBG:GetWidth())
    AuctionFrame.blanceBtn = CreateButton(nil, MLFrame, "结余", "LEFT", AuctionFrame.current, "RIGHT", 0, 0, 40)
    AuctionFrame.blanceBtn:SetScript("OnClick", function (self)
        ZL.AuctionRecordFrame:Show()
        _G["AuctionRecordFrameTab3"]:Click()
    end)
    AuctionFrame.blanceBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(AuctionFrame.histroy, "RIGHT", "LEFT", -8, 0)
        if ZL_CURRENT.playerBalance and next(ZL_CURRENT.playerBalance, nil) then
            GameTooltip:AddLine("当前结余记录：")
            GameTooltip:AddDoubleLine("玩家名字", "结余(g)")
            local index = 1
            for key, data in pairs(ZL_CURRENT.playerBalance) do
                if data["balance"] ~= 0 then
                    GameTooltip:AddDoubleLine(key, data["balance"], 1, 1, 1, 1, 1, 1)
                end
            end
        else
            GameTooltip:AddLine("当前没有结余记录！")
        end
        GameTooltip:Show()
    end)
    AuctionFrame.blanceBtn:SetScript("OnLeave", function () GameTooltip:Hide() end)
    AuctionFrame.RemainingTradeTimeBtn = CreateFrame("CheckButton", nil, AuctionFrame, "ChatConfigCheckButtonTemplate")
    AuctionFrame.RemainingTradeTimeBtn:SetPoint("LEFT", AuctionFrame.blanceBtn, "RIGHT", 0, 0)
    AuctionFrame.RemainingTradeTimeBtn.Text:SetText("交易时间")
    AuctionFrame.RemainingTradeTimeBtn.Text:SetFont(GameFontNormal:GetFont(), 12, "")
    AuctionFrame.RemainingTradeTimeBtn:SetHitRectInsets(0, -AuctionFrame.RemainingTradeTimeBtn.Text:GetWidth(), 0, 0)
    AuctionFrame.RemainingTradeTimeBtn.tooltip = "是否显示交易剩余时间"
    AuctionFrame.RemainingTradeTimeBtn:SetChecked(ZL.opt.remainingTradeTimeBtnValue)
    AuctionFrame.RemainingTradeTimeBtn:SetScript("OnClick", function (self)
        if ZL.AuctionFrame.RemainingTradeTimeBtn:GetChecked() then
            ZL.opt.remainingTradeTimeBtnValue = true
            ZL.RemainingTradeTimeFrame:Show()
            ZL.GetRemainingTradeTime()
            ZL.UpdateRemainingTradeTime =  C_Timer.NewTicker(30, function ()
                ZL.GetRemainingTradeTime()
            end)
        else
            ZL.opt.remainingTradeTimeBtnValue = false
            ZL.RemainingTradeTimeFrame:Hide()
            if ZL.UpdateRemainingTradeTime then
                ZL.UpdateRemainingTradeTime:Cancel()
            end
        end
    end)
    AuctionFrame.checkVerBtn = CreateButton(nil, MLFrame, "版本", "TOPLEFT", AuctionFrame.AllMinBtn, "BOTTOMLEFT", 0, 0, 40)
    AuctionFrame.checkVerBtn:SetScript("OnClick", function (self, button)
        if button == "LeftButton" and IsShiftKeyDown() then
            local msglist = {}
            local msgStr = ""
            local name
            for i = 1, GetNumGroupMembers() do
                name = GetRaidRosterInfo(i)
                if name then
                    if ZL_CURRENT.GroupMembersVersion[name] then
                        local ver = tonumber(ZL_CURRENT.GroupMembersVersion[name]:gsub("%.", ""))
                        local verSelf = tonumber(ZL.addonVersion:gsub("%.", ""))
                        if ver < verSelf then
                            msgStr = "您的【金团自动拍卖助手】版本过低，请及时更新升级"
                            table.insert(msglist, {msgStr=msgStr, name=name})
                        end
                    else
                        msgStr = "您还未安装【金团自动拍卖助手】，请及时下载，可极大提高拍卖效率"
                        table.insert(msglist, {msgStr=msgStr, name=name})
                    end
                end
            end
            local index = 1
            local function sendMessage()
                if index <= #msglist then
                    SendChatMessage(msglist[index].msgStr, "WHISPER", nil, msglist[index].name)
                    index = index + 1
                    C_Timer.After(2, sendMessage)
                end
            end
            sendMessage()
        else
            ZL_CURRENT.GroupMembersVersion = {}
            local data = {type="request"}
            MyAddon:TransmitAddonInfo("AUTOAUC VER", data)
        end
        self:Disable()
        C_Timer.After(3, function ()
            self:Enable()
        end)
    end)
    AuctionFrame.checkVerBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(AuctionFrame.AllMinBtn, "RIGHT","LEFT", -8, 0)
        GameTooltip:AddLine("插件版本检测：")
        GameTooltip:AddDoubleLine("玩家名", "版本号")
        if ZL_CURRENT.GroupMembersVersion then
            for i = 1, GetNumGroupMembers() do
                local name = GetRaidRosterInfo(i)
                if name and (not PlayerIsML(name)) then
                    if ZL_CURRENT.GroupMembersVersion[name] then
                        local ver = tonumber(ZL_CURRENT.GroupMembersVersion[name]:gsub("%.", ""))
                        local verSelf = tonumber(ZL.addonVersion:gsub("%.", ""))
                        if ver > verSelf then
                            GameTooltip:AddDoubleLine(name, ZL_CURRENT.GroupMembersVersion[name] .. "(↑)", 1, 1, 1, 1, 1, 1)
                        elseif ver < verSelf then
                            GameTooltip:AddDoubleLine(name, ZL_CURRENT.GroupMembersVersion[name] .. "|cffffd100(↓)|r", 1, 1, 1, 1, 1, 1)
                        else
                            GameTooltip:AddDoubleLine(name, ZL_CURRENT.GroupMembersVersion[name] .. "(→)", 1, 1, 1, 1, 1, 1)
                        end
                    else
                        GameTooltip:AddDoubleLine(name, "|cffffd100未安装|r", 1, 1, 1, 1, 1, 1)
                    end
                end
            end
        end
        GameTooltip:AddLine("   ")
        GameTooltip:AddLine("左键点击：|cffffffff检查团队成员插件版本情况|r")
        GameTooltip:AddLine("shift+左键点击：|cffffffff发送提醒|r")
        GameTooltip:AddLine("注意：|cffffffff3秒内最多点击一次|r")
        GameTooltip:Show()
    end)
    AuctionFrame.checkVerBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    AuctionFrame.auctionRules = CreateButton(nil, MLFrame, "规则", "LEFT", AuctionFrame.checkVerBtn, "RIGHT", 0, 0, 40)
    AuctionFrame.auctionRules:SetScript("OnClick", function (self)
        if IsShiftKeyDown() then
            LibStub("AceConfigDialog-3.0"):Open("金团自动拍卖助手")
        else
            if ZL.opt.rulesString then
                local announceStrings = emptytable("")
                for line in string.gmatch(ZL.opt.rulesString, "[^\n]+") do
                    for word in string.gmatch(line, "%S+") do
                        if strlen(announceStrings[#announceStrings]) + 1 + strlen(word) > 255 then
                            tinsert(announceStrings, word)
                        else
                            if strlen(announceStrings[#announceStrings]) > 0 then
                                announceStrings[#announceStrings] = announceStrings[#announceStrings] .. " " .. word
                            else
                                announceStrings[#announceStrings] = word
                            end
                        end
                    end
                    tinsert(announceStrings, "")
                end
                local index = 1
                local function sendMessage()
                    if index <= #announceStrings then
                        SendChatMessage(announceStrings[index], "RAID")
                        index = index + 1
                        C_Timer.After(0.3, sendMessage)
                    end
                end
                sendMessage()
                -- announceStrings:Release()
            else
                LibStub("AceConfigDialog-3.0"):Open("金团自动拍卖助手")
            end
        end
    end)
    AuctionFrame.auctionRules:SetScript("OnEnter", function (self)
        GameTooltipShow(AuctionFrame.AllMinBtn, "RIGHT", "LEFT", -8, 0)
        if ZL.opt.rulesString then
            local announceStrings = emptytable("")
            GameTooltip:AddLine("拍卖规则：")
            for line in string.gmatch(ZL.opt.rulesString, "[^\n]+") do
                for word in string.gmatch(line, "%S+") do
                    if strlen(announceStrings[#announceStrings]) + 1 + strlen(word) > 255 then
                        tinsert(announceStrings, word)
                    else
                        if strlen(announceStrings[#announceStrings]) > 0 then
                            announceStrings[#announceStrings] = announceStrings[#announceStrings] .. " " .. word
                        else
                            announceStrings[#announceStrings] = word
                        end
                    end
                end
                tinsert(announceStrings, "")
            end
            for _, msg in ipairs(announceStrings) do
                GameTooltip:AddLine(msg, 1, 1, 1)
            end
            GameTooltip:AddLine("   ")
            GameTooltip:AddLine("点击发送到团队频道")
            GameTooltip:AddLine("如需修改：Shift+左键点击——选择\"提示选项\"——修改拍卖规则")
            announceStrings:Release()
        else
            GameTooltip:AddLine("请先添加拍卖规则内容！")
            GameTooltip:AddLine("   ")
            GameTooltip:AddLine("点击——选择\"提示选项\"——输入拍卖规则")
        end
        GameTooltip:Show()
    end)
    AuctionFrame.auctionRules:SetScript("OnLeave", function () GameTooltip:Hide() end)
    AuctionFrame.syncBtn = CreateButton(nil, MLFrame, "同步", "LEFT", AuctionFrame.auctionRules, "RIGHT", 0, 0, 40)
    AuctionFrame.syncBtn:SetScript("OnClick", function (self)
        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
            for num, data in ipairs(ZL_CURRENT["auctionlist"]) do
                if data.state == "auctioning" and (not data.isPaused) then
                    data["isPaused"] = true
                    data.isPausedLinshi = true
                    local f = ZL.AuctionFrame.entries[num]
                    f.Frame1.timer:Pause()
                    f.Frame1.statetext:SetText("拍卖暂停中...")
                    f.Frame1.bidbox:Disable()
                    f.Frame1.bidBtn:Disable()
                    f.Frame1.autobidBtn:Disable()
                end
            end
            local data = {
                type = "同步所有",
                current = ZL_CURRENT,
            }
            MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
        end
        btnDelay(self)
    end)
    AuctionFrame.syncBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("慎用！")
        GameTooltip:AddLine("全团成员同步ML当前所有拍卖数据！", 1, 1, 1)
        GameTooltip:AddLine("使用场景：")
        GameTooltip:AddLine("当ML掉线后造成大量数据与其他成员不同步", 1, 1, 1)
        GameTooltip:Show()
    end)
    AuctionFrame.syncBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    AuctionFrame.failedBtn = CreateButton(nil, MLFrame, "流拍", "LEFT", AuctionFrame.syncBtn, "RIGHT", 0, 0, 40)
    AuctionFrame.failedBtn:SetScript("OnClick", function ()
        local msgStr = ""
        local failedCount = 0
        local msglist = {}
        if ZL_CURRENT.auctionlist and #ZL_CURRENT.auctionlist > 0 then
            for _, data in ipairs(ZL_CURRENT.auctionlist) do
                if data.state == "failed" then
                    failedCount = failedCount + data.itemCount
                    msgStr = data.itemlink .. "，数量：" .. data.itemCount
                    table.insert(msglist, msgStr)
                end
            end
            if failedCount > 0 then
                msgStr = "流拍总件数：" .. failedCount .. "件，详细清单如下："
                table.insert(msglist, 1, msgStr)
                msgStr = "以上流拍物品，如有需要的，请在团队频道发送物品链接！"
                table.insert(msglist, msgStr)
            else
                msgStr = "没有流拍的物品！"
                table.insert(msglist, msgStr)
            end
        else
            msgStr = "没有流拍的物品！"
            table.insert(msglist, msgStr)
        end
        local index = 1
        local function sendMessage()
            if index <= #msglist then
                SendChatMessage(msglist[index], "RAID")
                -- print(msglist[index])
                index = index + 1
                C_Timer.After(0.3, sendMessage)
            end
        end
        sendMessage()
    end)
    AuctionFrame.failedBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("流拍通报")
        GameTooltip:Show()
    end)
    AuctionFrame.failedBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    AuctionFrame.addAuctionBtn = CreateButton(nil, MLFrame, "创建", "LEFT", AuctionFrame.failedBtn, "RIGHT", 0, 0, 40)
    AuctionFrame.addAuctionBtn:SetScript("OnClick", function ()
        StaticPopup_Show("ZL_ADDAUCTIONITEM")
    end)
    AuctionFrame.addAuctionBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("手动创建拍卖物品，使用场景：")
        GameTooltip:AddLine("1、没被自动检测到的物品；", 1, 1, 1)
        GameTooltip:AddLine("2、拍卖打包的杂物(可以随便选择一个杂物，数量填写1)；", 1, 1, 1)
        GameTooltip:Show()
    end)
    AuctionFrame.addAuctionBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    AuctionFrame.reset = CreateButton(nil, MLFrame, "重置", "LEFT", AuctionFrame.addAuctionBtn, "RIGHT", 0, 0, 40)
    AuctionFrame.reset:SetScript("OnClick", function (self)
        --"您确定要重置当前拍卖记录么？确定将清空当前拍卖记录，并保存到历史记录中！"
        if ZL_CURRENT.auctionlist then
            local auctioningCount = 0
            local waitingCount = 0
            for _, data in ipairs(ZL_CURRENT.auctionlist) do
                if data.state == "auctioning" then
                    auctioningCount = auctioningCount + data.itemCount
                elseif data.state == "waiting" then
                    waitingCount = waitingCount + data.itemCount
                end
            end
            if auctioningCount > 0 then
                StaticPopup_Show("ZL_RESETCURRENTWARNING", auctioningCount)
                return
            end
            local msgStr = ""
            if waitingCount > 0 then
                msgStr = ("当前存在等待拍卖物品：%d个, 你确定要重置当前拍卖记录么？重置将清空当前拍卖记录，并保存到历史记录中！"):format(
                    waitingCount)
            else
                msgStr = "你确定要重置当前拍卖记录么？重置将清空当前拍卖记录，并保存到历史记录中！"
            end
            StaticPopup_Show("ZL_RESETCURRENT", msgStr, ZL_CURRENT.name)
        else
            GameTooltipShow(self, "BOTTOM", "TOP")
            GameTooltip:AddLine("当前没有拍卖记录！")
            GameTooltip:Show()
            C_Timer.After(3, function ()
                GameTooltip:Hide()
            end)
            print(Prefix("当前没有拍卖记录！"))
            MyAddon:TransmitAddonInfo("AUTOAUC RESET", "重置")
            ZL.TransmitAddonInfo_Pro()
        end
    end)
    AuctionFrame.add = CreateButton(nil, MLFrame, "+", "LEFT", AuctionFrame.reset, "RIGHT", 0, 0, 24)
    AuctionFrame.add:SetScript("OnClick", function (self)
        StaticPopup_Show("ZL_ADDINCOME", "收入", nil, "收入")
    end)
    AuctionFrame.add:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("手动录入|cffffd100【收入】|r", 1, 1, 1)
        GameTooltip:Show()
    end)
    AuctionFrame.add:SetScript("OnLeave", function (self) GameTooltip:Hide() end)
    AuctionFrame.rem= CreateButton(nil, MLFrame, "-", "LEFT", AuctionFrame.add, "RIGHT", 0, 0, 24)
    AuctionFrame.rem:SetScript("OnClick", function (self)
        StaticPopup_Show("ZL_ADDINCOME", "支出", nil, "支出")
    end)
    AuctionFrame.rem:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP")
        GameTooltip:AddLine("手动录入|cffffd100【支出】|r", 1, 1, 1)
        GameTooltip:Show()
    end)
    AuctionFrame.rem:SetScript("OnLeave", function (self) GameTooltip:Hide() end)
    --创建滚动条
    AuctionFrame.scrollFrame = CreateFrame("ScrollFrame", nil, AuctionFrame, "UIPanelScrollFrameTemplate")
    AuctionFrame.scrollFrame:SetFrameLevel(AuctionFrame:GetFrameLevel() + 1) -- 设置为比父框架高1级
    do
        local offsetY = 0
        if PlayerIsML() then
            offsetY = AuctionFrame.histroy:GetHeight() + AuctionFrame.AllMinBtn:GetHeight() + 8
        else
            offsetY = AuctionFrame.AllMinBtn:GetHeight() + 8
        end
        AuctionFrame.scrollFrame:SetPoint("TOPLEFT", _G["ZLAuctionFrameDialogBG"], "TOPLEFT", 3, -offsetY)
    end
    AuctionFrame.scrollFrame:SetPoint("BOTTOMRIGHT", _G["ZLAuctionFrameDialogBG"], "BOTTOMRIGHT", -3, 4)
    AuctionFrame.scrollFrame:SetClipsChildren(true) --必须设置为true，scrollFrame所有的子元素才会被剪切
    AuctionFrame.scrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel) --重设滑动条鼠标滚轮事件
    --重设ScrollBar位置，放置到scrollFrame内，防止被剪切掉
    AuctionFrame.scrollFrame.ScrollBar:ClearAllPoints()
    AuctionFrame.scrollFrame.ScrollBar:SetPoint("TOPLEFT", AuctionFrame.scrollFrame, "TOPRIGHT", -10, -15)
    AuctionFrame.scrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", AuctionFrame.scrollFrame, "BOTTOMRIGHT", -5, 15)
    AuctionFrame.scrollFrame.content = CreateFrame("Frame", nil, AuctionFrame.scrollFrame)
    local content = AuctionFrame.scrollFrame.content
    content:SetSize(AuctionFrame:GetWidth()- 38, 200)
    content:SetPoint("TOPLEFT", AuctionFrame.scrollFrame, "TOPLEFT")
    AuctionFrame.scrollFrame:SetScrollChild(content)

    --创建多TAB按钮点击事件函数
    local function Tab_OnClick(self)
        local frameParent = self:GetParent()
        local tableId = self:GetID()
        PanelTemplates_SetTab(frameParent, tableId)
        frameParent.tableId = tableId --将激活按钮的ID保存到AuctionFrame框架表里，用于显示对应的拍卖物品
        AuctionFrame:Update()
    end
    --创建多TAB按钮
    local function CreateTab(frame, numTabs, ...)
        frame.numTabs = numTabs
        local frameName = frame:GetName()
        for i = 1, numTabs do
            local template = ""
            if WOW_PROJECT_ID == 1 then
                template = "PanelTabButtonTemplate"
            elseif WOW_PROJECT_ID == 11 then
                template = "CharacterFrameTabButtonTemplate"
            end
            local tab = CreateFrame("Button", frameName.."Tab"..i, frame, template)
            local tooltip = select(i+numTabs, ...)
            tab:SetID(i)
            tab:SetText(select(i, ...))
            tab:SetScript("OnClick", Tab_OnClick)
            tab:SetScript("OnEnter", function (self)
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine(tooltip, 1, 1, 1)
                GameTooltip:Show()
            end)
            tab:SetScript("OnLeave", function ()
                GameTooltip:Hide()
            end)
            if WOW_PROJECT_ID == 1 then
                if i ==1 then
                    tab:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 5, 5)
                else
                    tab:SetPoint("TOPLEFT", _G[frameName.."Tab"..(i-1)], "TOPRIGHT", 0, 0)
                end
            elseif WOW_PROJECT_ID == 11 then
                if i ==1 then
                    tab:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 0, 5)
                else
                    tab:SetPoint("TOPLEFT", _G[frameName.."Tab"..(i-1)], "TOPRIGHT", -20, 0)
                end
            end
            
        end
    end
    --创建5个TAB按钮
    CreateTab(AuctionFrame, 5, "拍卖中", "成功", "流拍", "忽略", "待拍卖", "没有被忽略正在拍卖物品", "没有被忽略拍卖成功的物品", "没有被忽略流拍的物品", "被忽略的物品", "没有被忽略等待拍卖的物品")
    if (not PlayerIsML()) then
        -- _G["AuctionFrameTab5"]:Hide()
        MLFrame:Hide()
    else
        -- _G["AuctionFrameTab5"]:Show()
        MLFrame:Show()
    end
    AuctionFrame:Hide()

    AuctionFrame.entries = setmetatable({}, {
        __index = function (t, v)
            local ItemAuctionFrame = CreateFrame("Frame", nil, content, BackdropTemplateMixin and "BackdropTemplate")
            ItemAuctionFrame.maxAutoBid = nil --默认设置不自动出价
            ItemAuctionFrame:SetSize(content:GetWidth(), 200)
            ItemAuctionFrame:SetBackdrop({
                bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
                edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
                tileSize = 16,
                tile = true,
                edgeSize = 16,
                insets = { top = 5, bottom = 5, left = 5, right = 5 },
            })
            ItemAuctionFrame.titleBtn = CreateButton(nil, ItemAuctionFrame, "▲", "TOP", ItemAuctionFrame, "TOP", 0, 0, ItemAuctionFrame:GetWidth(), 20)
            ItemAuctionFrame.titleBtn:SetScript("OnEnter", function(self)
                GameTooltipShow(ItemAuctionFrame, "TOPLEFT", "TOPRIGHT")
                GameTooltip:SetHyperlink(ZL_CURRENT.auctionlist[v].itemlink)
                GameTooltip:Show()
            end)
            ItemAuctionFrame.titleBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)
            local fontString = ItemAuctionFrame.titleBtn:GetFontString()
            fontString:ClearAllPoints()
            fontString:SetPoint("RIGHT", ItemAuctionFrame.titleBtn, "RIGHT", -8, 0)
            ItemAuctionFrame.titleBtn:SetScript("OnClick", function (self)
                if ItemAuctionFrame.Frame1:IsShown() then
                    ItemAuctionFrame.Frame1:Hide()
                    ItemAuctionFrame.titleBtn:SetText("▼")
                else
                    ItemAuctionFrame.Frame1:Show()
                    ItemAuctionFrame.titleBtn:SetText("▲")
                end
                ItemAuctionFrame:UpdateItemAuctionFrame()
                AuctionFrame:Update()
            end)
            ItemAuctionFrame.titleBtn.itemname = ItemAuctionFrame.titleBtn:CreateFontString()
            ItemAuctionFrame.titleBtn.itemname:SetFont(GameFontNormal:GetFont(), 12, "OUTLINE")
            ItemAuctionFrame.titleBtn.itemname:SetTextColor(0.9, 0.9, 0.9)
            ItemAuctionFrame.titleBtn.itemname:SetPoint("LEFT", ItemAuctionFrame.titleBtn, "LEFT", 10, 0)
            ItemAuctionFrame.titleBtn.itemname:SetSize(ItemAuctionFrame:GetWidth()-50, ItemAuctionFrame.titleBtn:GetHeight())
            ItemAuctionFrame.titleBtn.itemname:SetWordWrap(false)
            ItemAuctionFrame.titleBtn.itemname:SetJustifyH("LEFT")
            ItemAuctionFrame.Frame1 = CreateFrame("Frame", nil, ItemAuctionFrame)
            local Frame1 = ItemAuctionFrame.Frame1
            Frame1:SetPoint("TOP", ItemAuctionFrame.titleBtn, "BOTTOM")
            Frame1:SetWidth(ItemAuctionFrame:GetWidth())
            Frame1.icon = Frame1:CreateTexture(nil, "OVERLAY")
            local icon = Frame1.icon
            icon:SetSize(46, 46)
            icon:SetPoint("TOPLEFT", Frame1, "TOPLEFT", 10, -5)
            Frame1.iconBtn = CreateFrame("Button", nil, Frame1)
            Frame1.iconBtn:SetAllPoints(icon)
            Frame1.iconBtn:SetScript("OnEnter", function(self)
                GameTooltipShow(self, "RIGHT", "LEFT", -10)
                GameTooltip:SetHyperlink(ZL_CURRENT.auctionlist[v].itemlink)
                GameTooltip:Show()
            end)
            Frame1.iconBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)

            --在图标上显示倒计时
            Frame1.timer = CreateFrame("Cooldown", nil, ZL, "CooldownFrameTemplate") --父对象为ZL，防止隐藏的时候无法触发"OnCooldownDone" 
            local timer = Frame1.timer
            timer:SetReverse(true)
            timer:SetAllPoints(icon)
            timer:SetDrawEdge(false)  -- 显示边缘动画
            timer:SetDrawSwipe(false)  -- 显示旋转动画
            timer:SetDrawBling(false)  -- 显示闪光动画
            timer:SetHideCountdownNumbers(true)  -- 隐藏默认的倒计时数字
            timer:SetSwipeColor(0, 0, 0, 0.5)-- 设置旋转动画透明度
            -- timer:SetFrameStrata("DIALOG")
            -- 在冷却时间结束时停止更新, cooldown窗口倒计时结束不能发送消息，函数保护
            timer:HookScript("OnCooldownDone", function(self)
                timer.updateframe:Hide()
                --ML开始发送拍卖结果，自动发言只能在raid/party/guild频道, 在副本的时候SAY/YELL也能自动化
                --不能放在timer.updateframe自动发信息，否则取消拍卖时也会触发下面的发送信息
                if PlayerIsML() then
                    local curAuctionList = ZL_CURRENT.auctionlist[v]
                    local msgStr = ""
                    local bidderlist =curAuctionList.bidderlist
                    if #bidderlist > 0 then --如果有人出价
                        tableSort(bidderlist)
                        for i = 1, math.min(curAuctionList.itemCount, #bidderlist) do
                            msgStr = msgStr .. bidderlist[i].bidder .. "(" .. bidderlist[i].bidamount .. "g)，"
                        end
                        msgStr = ("%s拍卖成功！获胜者：%s祝贺！"):format(curAuctionList.itemlink, msgStr)
                        SendChatMessage(msgStr, "RAID")
                        -- print(msgStr)
                        local data = {
                            type = "拍卖成功",
                            itemindex = curAuctionList.itemindex,
                            itemId = curAuctionList.itemId,
                            itemlink = curAuctionList.itemlink,
                        }
                        MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                    else
                        msgStr = ("%s 流拍！"):format(curAuctionList.itemlink)
                        SendChatMessage(msgStr, "RAID")
                        local data = {
                            type = "流拍",
                            itemindex = curAuctionList.itemindex,
                            itemId = curAuctionList.itemId,
                        }
                        MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                    end
                end
            end)

            -- 创建一个frame和字符串来更新和显示冷却时间
            timer.cooldownText = Frame1:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
            timer.cooldownText:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", -2, 2)
            timer.cooldownText:SetSize(icon:GetWidth()-4, 10)
            timer.cooldownText:SetFont(GameFontNormal:GetFont(), 10)
            timer.cooldownText:SetWordWrap(false)
            timer.cooldownText:SetJustifyH("RIGHT")
            timer.updateframe = CreateFrame("Frame", nil ,ZL)
            timer.updateframe:Hide()
            timer.updateframe:SetScript("OnUpdate", function (self)
                if  (not timer:IsPaused()) then
                    local start, duration = timer:GetCooldownTimes()
                    local remaining = (start + duration - GetTime() * 1000) / 1000
                    if remaining >= 0 then
                        timer.cooldownText:SetText(ConvertSecondsToTime(math.ceil(remaining)))
                        if remaining >= 3599 then
                            timer.cooldownText:SetFont(GameFontNormal:GetFont(), 10)
                        elseif remaining >= 59 then
                            timer.cooldownText:SetFont(GameFontNormal:GetFont(), 13)
                        else
                            timer.cooldownText:SetFont(GameFontNormal:GetFont(), 18)
                        end
                        ZL_CURRENT.auctionlist[v]["countdownremaining"] = math.ceil(remaining)
                        if ItemAuctionFrame.maxAutoBid then
                            ItemAuctionFrame.autoBidStart = ItemAuctionFrame.autoBidStart or GetTime()
                            if (ItemAuctionFrame.autoBidStart + 2 - GetTime()) <= 0 then
                                autoBid(v, ItemAuctionFrame.maxAutoBid)
                                ItemAuctionFrame.autoBidStart = GetTime()
                            end
                        end
                        if PlayerIsML() then 
                            ItemAuctionFrame.daoShuStart = ItemAuctionFrame.daoShuStart or GetTime()
                            --1分钟提醒
                            -- if remaining <= 60 and (not timer.oneMinuteWarn) then
                            --     local msgStr = ""
                            --     local curAuctionList = ZL_CURRENT.auctionlist[v]
                            --     msgStr = ("[%d]%s最后%d秒提醒，请及时出价！"):format(curAuctionList.itemindex, curAuctionList.itemlink, 60)
                            --     SendChatMessage(msgStr, "RAID")
                            --     -- print(msgStr)
                            --     timer.oneMinuteWarn = true
                            -- end
                            --5秒倒计时
                            if (remaining <= 5) and (ItemAuctionFrame.daoShuStart + 1 - GetTime() <= 0) then
                                local msgStr = ""
                                local curAuctionList = ZL_CURRENT.auctionlist[v]
                                local bidderlist = ZL_CURRENT.auctionlist[v].bidderlist
                                local tarbidamount = 0
                                tableSort(bidderlist)
                                if bidderlist[curAuctionList.itemCount] then
                                    tarbidamount = bidderlist[curAuctionList.itemCount].bidamount + curAuctionList.bidIncrement
                                else
                                    tarbidamount = curAuctionList.startbidamount
                                end
                                if #bidderlist > 0 then
                                    for i = 1, math.min(curAuctionList.itemCount, #bidderlist) do
                                        msgStr = msgStr .. bidderlist[i].bidamount .. "g，"
                                    end
                                    -- msgStr = ("[%d]%s 有效出价：%s下次最低出价：%dg，倒数：%d"):format(
                                    --     curAuctionList.itemindex, curAuctionList.itemlink, msgStr, tarbidamount, math.ceil(remaining)
                                    -- )
                                    msgStr = ("%s%s倒数：%d"):format(
                                        curAuctionList.itemlink, msgStr, math.ceil(remaining)
                                    )
                                    SendChatMessage(msgStr, "RAID")
                                else
                                    -- msgStr = ("[%d]%s无人出价！下次最低出价：%dg，倒数：%d" ):format(
                                    --     curAuctionList.itemindex, curAuctionList.itemlink, tarbidamount, math.ceil(remaining)
                                    -- )
                                    msgStr = ("%s，倒数：%d" ):format(
                                        curAuctionList.itemlink, math.ceil(remaining)
                                    )
                                    SendChatMessage(msgStr, "RAID")
                                end
                                ItemAuctionFrame.daoShuStart = GetTime()
                            end
                        end
                    else
                        timer.cooldownText:SetText("")
                        ZL_CURRENT.auctionlist[v]["countdownremaining"] = 0
                    end
                end
            end)
            local fontwidth = Frame1:GetWidth() - icon:GetWidth() - 25
            Frame1.statetext = Frame1:CreateFontString()
            local statetext = Frame1.statetext
            statetext:SetPoint("TOPLEFT", icon, "TOPRIGHT", 5, 0)
            statetext:SetFont(GameFontNormal:GetFont(), 12, "OUTLINE")
            statetext:SetTextColor(1, 1, 1)
            statetext:SetWidth(fontwidth)
            statetext:SetWordWrap(false)
            statetext:SetJustifyH("LEFT")
            Frame1.curbidamounttext = Frame1:CreateFontString()
            local curbidamounttext = Frame1.curbidamounttext
            curbidamounttext:SetPoint("TOPLEFT", statetext, "BOTTOMLEFT", 0, -5)
            curbidamounttext:SetFont(GameFontNormal:GetFont(), 12, "OUTLINE")
            curbidamounttext:SetTextColor(1, 1, 1)
            curbidamounttext:SetWidth(fontwidth)
            curbidamounttext:SetWordWrap(false)
            curbidamounttext:SetJustifyH("LEFT")
            Frame1.curbiddertext = Frame1:CreateFontString()
            local curbiddertext = Frame1.curbiddertext
            curbiddertext:SetPoint("TOPLEFT", curbidamounttext, "BOTTOMLEFT", 0, -5)
            curbiddertext:SetFont(GameFontNormal:GetFont(), 10, "OUTLINE")
            curbiddertext:SetTextColor(1, 1, 1)
            curbiddertext:SetWidth(fontwidth)
            curbiddertext:SetWordWrap(false)
            curbiddertext:SetJustifyH("LEFT")
            Frame1.toolFrame = CreateFrame("Frame", nil, Frame1)
            local toolFrame = Frame1.toolFrame
            toolFrame:SetPoint("TOPLEFT", curbidamounttext, "TOPLEFT")
            toolFrame:SetPoint("BOTTOMRIGHT", curbiddertext, "BOTTOMRIGHT")
            toolFrame:SetScript("OnEnter", function (self)
                local bidderlist = ZL_CURRENT.auctionlist[v].bidderlist
                tableSort(bidderlist)
                if bidderlist and (#bidderlist > 0) then
                    GameTooltipShow(self, "LEFT", "RIGHT", 8, 0)
                    GameTooltip:AddLine("当前出价记录：")
                    GameTooltip:AddDoubleLine("玩家名", "出价金额(g)")
                    for _, data in ipairs(bidderlist) do
                        GameTooltip:AddDoubleLine(data["bidder"], data["bidamount"], 1, 1, 1, 1, 1, 1)
                    end
                    GameTooltip:Show()
                end
                
            end)
            toolFrame:SetScript("OnLeave", function ()
                GameTooltip:Hide()
            end)
            Frame1.bidbox = CreateFrame("EditBox", nil, Frame1, BackdropTemplateMixin and "BackdropTemplate")
            local bidbox = Frame1.bidbox
            bidbox:SetMultiLine(false)
            bidbox:SetBackdrop({ bgFile = "Interface\\ChatFrame\\UI-ChatInputBorder", tile = false })
            bidbox:SetTextInsets(5, 5, 2, 2)
            bidbox:SetSize(70, 26)
            bidbox:SetFont(GameFontNormal:GetFont(), 12, "")
            bidbox:SetAutoFocus(false)
            bidbox:SetPoint("TOPLEFT", icon, "BOTTOMLEFT", 0, -5)
            bidbox:SetJustifyH("RIGHT")
            bidbox:SetNumeric(true)
            bidbox:SetNumber(0)
            bidbox:SetScript("OnMouseWheel", function(self, delta)
                if self:HasFocus() then
                    local number = self:GetNumber()
                    if delta > 0 then
                        number = number + ZL_CURRENT.auctionlist[v].bidIncrement
                    else
                        number = number - ZL_CURRENT.auctionlist[v].bidIncrement
                    end
                    self:SetNumber(number)
                end
            end)
            bidbox:SetScript("OnEnter", function(self)
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("目标出价")
                GameTooltip:AddLine("激活输入框，输入或用鼠标滚轮设定目标价\n按Enter键或鼠标中键直接竞价", 1, 1, 1)
                GameTooltip:Show()
            end)
            bidbox:SetScript("OnLeave", function() GameTooltip:Hide() end)
            bidbox:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
            local function bidboxfunc(self)
                local wantBid = self:GetNumber()
                local curAuctionList = ZL_CURRENT.auctionlist[v]
                local bidderlist = ZL_CURRENT.auctionlist[v].bidderlist
                local newBid = 0
                local isSelf = false
                tableSort(bidderlist)
                if bidderlist and (#bidderlist > 0) then
                    for i = 1, math.min(#bidderlist, curAuctionList.itemCount) do
                        if bidderlist[i].bidder == UnitName("player") then
                            isSelf = true
                        end
                    end
                end
                if (not isSelf) then
                    if bidderlist[curAuctionList.itemCount] then
                        newBid = bidderlist[curAuctionList.itemCount].bidamount + curAuctionList.bidIncrement
                    else
                        newBid = curAuctionList.startbidamount
                    end
                    if wantBid >= newBid then
                        SendChatMessage(curAuctionList.itemlink .. wantBid, "RAID")
                    else
                        print(Prefix("出价过低，至少出价：" .. newBid .."g"))
                        GameTooltipShow(self, "BOTTOM", "TOP")
                        GameTooltip:AddLine("出价过低，至少出价：|cffffd100" .. newBid .."|rg", 1, 1, 1)
                        GameTooltip:Show()
                        C_Timer.After(3, function ()
                            GameTooltip:Hide()
                        end)
                    end
                else
                    GameTooltip:ClearAllPoints()
                    GameTooltip:ClearLines()
                    GameTooltip:SetOwner(self, "ANCHOR_NONE")
                    GameTooltip:AddLine("你已经是有效最高出价者，无需竞价！")
                    GameTooltip:SetPoint("BOTTOM", self, "TOP")
                    GameTooltip:Show()
                    C_Timer.After(3, function ()
                        GameTooltip:Hide()
                    end)
                end
                self:ClearFocus()
            end
            bidbox:SetScript("OnEnterPressed", bidboxfunc)
            bidbox:SetScript("OnMouseDown", function(self, button)
                if button == "MiddleButton" then
                    if self:HasFocus() then
                        bidboxfunc(self)
                    end
                end
            end)
            bidbox:Disable()
            Frame1.bidBtn = CreateButton(nil, Frame1, "单次出价", "LEFT", bidbox, "RIGHT")
            local bidBtn = Frame1.bidBtn
            bidBtn:SetScript("OnEnter", function(self)
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("按照每次最低加价幅度|cffffd100" .. ZL_CURRENT.auctionlist[v].bidIncrement .. "g|r竞价", 1, 1, 1)
                GameTooltip:Show()
            end)
            bidBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)
            bidBtn:SetScript("OnClick", function(self)
                local newBid = 0
                local curAuctionList = ZL_CURRENT.auctionlist[v]
                local bidderlist = ZL_CURRENT.auctionlist[v].bidderlist
                local isSelf = false
                tableSort(bidderlist)
                if bidderlist and (#bidderlist > 0) then
                    for i = 1, math.min(#bidderlist, curAuctionList.itemCount) do
                        if bidderlist[i].bidder == UnitName("player") then
                            isSelf = true
                        end
                    end
                end
                if (not isSelf) then
                    if bidderlist[curAuctionList.itemCount] then
                        newBid = bidderlist[curAuctionList.itemCount].bidamount + curAuctionList.bidIncrement
                    else
                        newBid = curAuctionList.startbidamount
                    end
                    SendChatMessage(curAuctionList.itemlink .. newBid, IsInRaid() and "RAID" or "SAY")
                else
                    GameTooltip:ClearAllPoints()
                    GameTooltip:ClearLines()
                    GameTooltip:SetOwner(self, "ANCHOR_NONE")
                    GameTooltip:AddLine("你已经是有效最高出价者，无需竞价！")
                    GameTooltip:SetPoint("BOTTOM", self, "TOP")
                    GameTooltip:Show()
                    C_Timer.After(3, function ()
                        GameTooltip:Hide()
                    end)
                end
                -- btnDelay(self)
            end)
            bidBtn:Disable()
            Frame1.autobidBtn = CreateButton(nil, Frame1, "自动出价", "LEFT", bidBtn, "RIGHT")
            local autobidBtn = Frame1.autobidBtn
            autobidBtn:SetScript("OnClick", function(self)
                local curAuctionList = ZL_CURRENT.auctionlist[v]
                if autobidBtn:GetText() == "自动出价" then
                    local data = {index=v, f=ItemAuctionFrame}
                    StaticPopup_Show("ZL_AUTOBID", curAuctionList.itemlink).data = data
                else
                    ItemAuctionFrame.maxAutoBid = nil
                    autobidBtn:SetText("自动出价")
                    Frame1.bidbox:Enable()
                    Frame1.bidBtn:Enable()
                    Frame1.lgnoreBtn:Enable()
                end
            end)
            autobidBtn:SetScript("OnEnter", function (self)
                if ItemAuctionFrame.maxAutoBid then
                    GameTooltipShow(self, "BOTTOM", "TOP")
                    GameTooltip:AddLine("最大出价：|cffffd100" .. ItemAuctionFrame.maxAutoBid .."|rg", 1, 1, 1)
                    GameTooltip:AddLine("  ")
                    GameTooltip:AddLine("如出现角色无法移动，连续按几次Enter键！")
                    GameTooltip:Show()
                else
                    GameTooltipShow(self, "BOTTOM", "TOP")
                    GameTooltip:AddLine("注意：")
                    GameTooltip:AddLine("使用自动出价可能存在角色无法移动！")
                    GameTooltip:AddLine("连续按几次Enter键可解决！")
                    GameTooltip:AddLine("为避免刷屏，非必要尽量少用！")
                    GameTooltip:AddLine("   ")
                    GameTooltip:AddLine("设置最大目标价后，如不是有效最高出价者，\n则每2秒按照最低加价幅度竞价", 1, 1, 1)
                    GameTooltip:Show()
                end
            end)
            autobidBtn:SetScript("OnLeave", function ()
                GameTooltip:Hide()
            end)
            autobidBtn:Disable()
            Frame1.lgnoreBtn = CreateButton(nil, Frame1, "忽略", "LEFT", autobidBtn, "RIGHT", 0, 0, 40)
            local lgnoreBtn = Frame1.lgnoreBtn
            lgnoreBtn:SetScript("OnClick", function(self)
                if lgnoreBtn:GetText() == "忽略" then
                    lgnoreBtn:SetText("恢复")
                    ZL_CURRENT.auctionlist[v].lgnore = true
                else
                    lgnoreBtn:SetText("忽略")
                    ZL_CURRENT.auctionlist[v].lgnore = false
                end
                AuctionFrame:Update()
            end)
            --以下为ML权限
            Frame1.MLframe = CreateFrame("Frame", nil, Frame1)
            local MLframe = Frame1.MLframe
            MLframe:SetPoint("TOPLEFT", bidbox, "BOTTOMLEFT", -5, -2)
            MLframe:SetWidth(ItemAuctionFrame:GetWidth())
            MLframe:SetScript("OnShow", function (self)
                local startbid, increment = GetStartAndIncrementBid(ZL_CURRENT.auctionlist[v].itemId)
                local startbidEditboxNum = self.startbidEditbox:GetNumber() or 0
                local incrementEditboxNum = self.incrementEditbox:GetNumber() or 0
                if startbidEditboxNum <= 0 then self.startbidEditbox:SetNumber(startbid) end
                if incrementEditboxNum <= 0 then self.incrementEditbox:SetNumber(increment) end
            end)

            MLframe.startbidFont = MLframe:CreateFontString()
            MLframe.startbidFont:SetPoint("TOPLEFT", MLframe, "TOPLEFT", 5, -3)
            MLframe.startbidFont:SetFont(GameFontNormal:GetFont(), 10)
            MLframe.startbidFont:SetTextColor(1, 1, 1)
            MLframe.startbidFont:SetText("起拍价:")
            MLframe.startbidFont:SetWordWrap(false)
            MLframe.startbidFont:SetJustifyH("LEFT")
            MLframe.startbidEditbox = CreateFrame("EditBox", nil, MLframe, "InputBoxTemplate")
            local startbidEditbox  = MLframe.startbidEditbox
            startbidEditbox:SetPoint("LEFT", MLframe.startbidFont, "RIGHT", 8, 0)
            startbidEditbox:SetSize(45, 20)
            startbidEditbox:SetAutoFocus(false)
            startbidEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
            startbidEditbox:SetNumeric(true)
            startbidEditbox:SetScript("OnEnterPressed", function (self)
                self:ClearFocus()
            end)

            MLframe.inrementFont = MLframe:CreateFontString() --nil, "OVERLAY"
            MLframe.inrementFont:SetPoint("LEFT", startbidEditbox, "RIGHT", 5, 0)
            MLframe.inrementFont:SetFont(GameFontNormal:GetFont(), 10)
            MLframe.inrementFont:SetTextColor(1, 1, 1)
            MLframe.inrementFont:SetText("加价:")
            MLframe.inrementFont:SetWordWrap(false)
            MLframe.inrementFont:SetJustifyH("LEFT")
            MLframe.incrementEditbox = CreateFrame("EditBox", nil, MLframe, "InputBoxTemplate")
            local incrementEditbox  = MLframe.incrementEditbox
            incrementEditbox:SetPoint("LEFT", MLframe.inrementFont, "RIGHT", 8, 0)
            incrementEditbox:SetSize(40, 20)
            incrementEditbox:SetAutoFocus(false)
            incrementEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
            incrementEditbox:SetNumeric(true)
            incrementEditbox:SetScript("OnEnterPressed", function (self)
                self:ClearFocus()
            end)
            MLframe.filterBtn = CreateButton(nil, MLframe, "过滤", "LEFT", incrementEditbox, "RIGHT", 5, 0, 40)
            MLframe.filterBtn:SetScript("OnClick", function ()
                local itemId = ZL_CURRENT.auctionlist[v].itemId
                local isExist = false
                local filterFrame = ZL.ItemSettingFrame.filterFrame
                for _, data in ipairs(ZL_SETTING.filterItemId) do
                    if data.itemId == itemId then
                        isExist = true
                    end
                end
                if (not isExist) then
                    local itemlink = select(2, cGetItemInfo(itemId))
                    if itemlink then
                        table.insert(ZL_SETTING.filterItemId, {itemId=itemId, itemlink=itemlink})
                        if filterFrame:Show() then
                            filterFrame:Update()
                        end
                        if lgnoreBtn:GetText() == "忽略" then
                            lgnoreBtn:Click()
                        end
                    else
                        print(Prefix("未查询到物品ID信息，请核实填写是否正确！"))
                        GameTooltipShow(self, "BOTTOM", "TOP")
                        GameTooltip:AddLine("未查询到物品ID信息，请核实填写是否正确！")
                        GameTooltip:Show()
                        C_Timer.After(3, function ()
                            GameTooltip:Hide()
                        end)
                    end
                else
                    if lgnoreBtn:GetText() == "忽略" then
                        lgnoreBtn:Click()
                    end
                    print(Prefix("物品已存在！"))
                end
            end)
            MLframe.filterBtn:SetScript("OnEnter", function (self)
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("过滤后，下次将不再自动创建拍卖！")
                GameTooltip:AddLine("如需恢复：可到物品设置——过滤中删除", 1, 1, 1)
                GameTooltip:Show()
            end)
            MLframe.filterBtn:SetScript("OnLeave", function ()
                GameTooltip:Hide()
            end)
            MLframe.syncBtn = CreateButton(nil, MLframe, "同步", "LEFT", MLframe.filterBtn, "RIGHT", 0, 0, 40)
            MLframe.syncBtn:SetScript("OnClick", function (self)
                if ZL_CURRENT.auctionlist[v].state == "auctioning" and (not ZL_CURRENT.auctionlist[v]["isPaused"]) then
                    ZL_CURRENT.auctionlist[v]["isPaused"] = true
                    ZL_CURRENT.auctionlist[v].isPausedLinshi = true
                    local f = AuctionFrame.entries[v]
                    f.Frame1.timer:Pause()
                    f.Frame1.statetext:SetText("拍卖暂停中...")
                    f.Frame1.bidbox:Disable()
                    f.Frame1.bidBtn:Disable()
                    f.Frame1.autobidBtn:Disable()
                end
                local data = {
                    type = "同步单个",
                    curAuction = ZL_CURRENT.auctionlist[v],
                }
                MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                btnDelay(self)
            end)
            MLframe.syncBtn:SetScript("OnEnter", function (self)
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("全团成员同步ML单个拍卖物品数据", 1, 1, 1)
                GameTooltip:Show()
            end)
            MLframe.syncBtn:SetScript("OnLeave", function ()
                GameTooltip:Hide()
            end)
            MLframe.PauseBtn = CreateButton(nil, MLframe, "暂停", "TOPLEFT", MLframe.startbidFont, "BOTTOMLEFT", 0, -5, 40)
            MLframe.PauseBtn:SetScript("OnClick", function (self)
                local curAuctionList = ZL_CURRENT.auctionlist[v]
                if self:GetText() == "暂停" then
                    self:SetText("继续")
                    -- SendChatMessage(("[%d]%s已暂停拍卖！"):format(curAuctionList.itemindex, curAuctionList.itemlink), "RAID")
                    SendChatMessage(("%s已暂停拍卖！"):format(curAuctionList.itemlink), "RAID")
                    local data = {
                        type = "暂停拍卖",
                        itemId = curAuctionList.itemId,
                        itemindex = curAuctionList.itemindex,
                    }
                    MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                else
                    local msgStr = ""
                    local newBid = 0
                    local bidderlist = ZL_CURRENT.auctionlist[v].bidderlist
                    self:SetText("暂停")
                    tableSort(bidderlist)
                    if bidderlist[curAuctionList.itemCount] then
                        newBid = bidderlist[curAuctionList.itemCount].bidamount + curAuctionList.bidIncrement
                    else
                        newBid = curAuctionList.startbidamount
                    end
                    if #bidderlist > 0 then
                        for i = 1, math.min(curAuctionList.itemCount, #bidderlist) do
                            msgStr = msgStr .. bidderlist[i].bidamount .. "g，"
                        end
                        msgStr = ("%s已恢复拍卖，有效出价：%s下次最低出价：%d"):format(
                            curAuctionList.itemlink, msgStr, newBid
                        )
                        SendChatMessage(msgStr, "RAID")
                    else
                        SendChatMessage(("%s已恢复拍卖，当前无人出价，起拍价：%d，每次最低加价：%d"):format(
                            curAuctionList.itemlink, curAuctionList.startbidamount,
                            curAuctionList.bidIncrement), "RAID")
                    end
                    local data = {
                        type = "继续拍卖",
                        itemId = curAuctionList.itemId,
                        itemindex = curAuctionList.itemindex,
                    }
                    MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                end
                btnDelay(self)
            end)
            MLframe.PauseBtn:Disable()
            MLframe.CancelBtn = CreateButton(nil, MLframe, "开始", "LEFT", MLframe.PauseBtn, "RIGHT", 0, 0, 40) --取消开始同一个按钮
            MLframe.CancelBtn:SetScript("OnClick", function (self)
                local curAuctionList = ZL_CURRENT.auctionlist[v]
                if self:GetText() == "取消" then
                    self:SetText("开始")
                    SendChatMessage(("%s拍卖已取消，本次拍卖无效，等待重新拍卖！"):format(curAuctionList.itemlink), "RAID")
                    local data = {
                        type = "取消拍卖",
                        itemindex = curAuctionList.itemindex,
                        itemlink = curAuctionList.itemlink,
                        itemId = curAuctionList.itemId,
                    }
                    MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                else
                    if (not ZL.opt.allowMultipleAuctions) and (GetAuctioningCount() >= 1 )then
                        GameTooltipShow(self, "BOTTOM", "TOP")
                        GameTooltip:AddLine("当前为单拍模式，不允许同时拍卖多个物品！")
                        GameTooltip:Show()
                        C_Timer.After(3, function ()
                            GameTooltip:Hide()
                        end)
                        return
                    end
                    local isExist = false --判断是否有相同物品正在拍卖中
                    if ZL_CURRENT.auctionlist then
                        for _, data in ipairs(ZL_CURRENT.auctionlist) do
                            if (data.index ~= v) and (data.itemId == curAuctionList.itemId) and (data.state == "auctioning") then
                                isExist = true
                                break
                            end
                        end
                    end
                    if isExist then
                        GameTooltipShow(self, "BOTTOM", "TOP")
                        GameTooltip:AddLine("已有相同的物品正在拍卖，无法同时进行！")
                        GameTooltip:Show()
                        C_Timer.After(3, function ()
                            GameTooltip:Hide()
                        end)
                        print(Prefix("已有相同的物品正在拍卖，无法同时进行！"))
                    else
                        self:SetText("取消")
                        -- SendChatMessage(("开始拍卖[%d]%s×%d，起拍价：%dg，最低加价：%dg"):format(
                        --     curAuctionList.itemindex, curAuctionList.itemlink, curAuctionList.itemCount, MLframe.startbidEditbox:GetNumber(),
                        --     MLframe.incrementEditbox:GetNumber()), "RAID")
                        if curAuctionList.itemCount == 1 then
                            SendChatMessage(("%s，起拍价：%d，最低加价：%d"):format(
                                curAuctionList.itemlink, MLframe.startbidEditbox:GetNumber(), MLframe.incrementEditbox:GetNumber()), "RAID")
                        else
                            SendChatMessage(("%s×%d，起拍价：%d，最低加价：%d"):format(
                                curAuctionList.itemlink, curAuctionList.itemCount, MLframe.startbidEditbox:GetNumber(),
                                MLframe.incrementEditbox:GetNumber()), "RAID")
                        end
                        local data = {
                            type = "开始拍卖",
                            itemindex = curAuctionList.itemindex,
                            itemlink = curAuctionList.itemlink,
                            itemCount = curAuctionList.itemCount,
                            startbidamount = MLframe.startbidEditbox:GetNumber(),
                            bidIncrement = MLframe.incrementEditbox:GetNumber(),
                            auctionTimer = ZL.opt.auctionTimer,
                            itemId = curAuctionList.itemId,
                        }
                        MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                    end
                end
                btnDelay(self)
            end)
            MLframe.CountDownBtn = CreateButton(nil, MLframe, "倒数", "LEFT", MLframe.CancelBtn, "RIGHT", 0, 0, 40)
            MLframe.CountDownBtn:SetScript("OnClick", function (self)
                timer.oneMinuteWarn = true --手动重置倒计时后不再自动1分钟提醒
                local curAuctionList = ZL_CURRENT.auctionlist[v]
                SendChatMessage(("%s最后%d秒倒计时，请及时出价！"):format(
                    curAuctionList.itemlink, ZL.opt.manualCountdownTimer), "RAID")
                local data = {
                    type = "手动倒计时",
                    itemindex = curAuctionList.itemindex,
                    itemId = curAuctionList.itemId,
                    manualCountdownTimer = ZL.opt.manualCountdownTimer,
                }
                MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                btnDelay(self)
            end)
            MLframe.CountDownBtn:SetScript("OnEnter", function (self)
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("手动|cffffffff" .. ZL.opt.manualCountdownTimer .. "|r秒倒计时")
                GameTooltip:AddLine("注意：将重置倒计时，并且不再自动1分钟提醒！", 1, 1, 1)
                GameTooltip:Show()
            end)
            MLframe.CountDownBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)
            MLframe.CountDownBtn:Disable()
            MLframe.reverseBidBtn = CreateButton(nil, MLframe, "撤销出价", "LEFT", MLframe.CountDownBtn, "RIGHT")
            MLframe.reverseBidBtn:SetScript("OnClick", function (self)
                local curAuctionList = ZL_CURRENT.auctionlist[v]
                local bidderlist = ZL_CURRENT.auctionlist[v].bidderlist
                if bidderlist and #bidderlist > 0 then
                    local data = {itemId=curAuctionList.itemId, itemindex=curAuctionList.itemindex}
                    StaticPopup_Show("ZL_REVOKEBID").data = data
                    btnDelay(self)
                else
                    print(Prefix("当前无人出价！"))
                    GameTooltipShow(self, "BOTTOM", "TOP")
                    GameTooltip:AddLine("当前无人出价！")
                    GameTooltip:Show()
                    C_Timer.After(3, function ()
                        GameTooltip:Hide()
                    end)
                end
            end)
            MLframe:SetHeight(startbidEditbox:GetHeight() + MLframe.PauseBtn:GetHeight() + 10)
            MLframe.reverseBidBtn:Disable()
            --ML权限结束

            --更新物品拍卖子窗口
            function ItemAuctionFrame:UpdateItemAuctionFrame()
                do
                    if (not PlayerIsML()) then
                        MLframe:Hide()
                    else
                        MLframe:Show()
                    end
                    local height = icon:GetHeight() + bidbox:GetHeight() + 10
                    if MLframe:IsShown() then
                        height = height + MLframe:GetHeight()
                    else
                        height = height + 8
                    end
                    Frame1:SetHeight(height)
                end
                do
                    local height = self.titleBtn:GetHeight()
                    if Frame1:IsShown() then
                        height = height + Frame1:GetHeight()
                    end
                    self:SetHeight(height)
                end
            end
            function ItemAuctionFrame:SetValues(index)
                local curAuctionList = ZL_CURRENT.auctionlist
                self.index = index  --框架在数组中的索引
                local itemId = curAuctionList[index].itemId
                local itemlink = curAuctionList[index].itemlink
                local itemindex = curAuctionList[index].itemindex
                local state = curAuctionList[index].state
                local countdownremaining = curAuctionList[index].countdownremaining
                local isPaused = curAuctionList[index].isPaused
                local itemCount = curAuctionList[index].itemCount
                local bidderlist = curAuctionList[index].bidderlist
                local lgnore = curAuctionList[index].lgnore
                ItemAuctionFrame.titleBtn.itemname:SetText("[" .. itemindex .. "] " .. itemCount .. "×" .. itemlink)
                icon:SetTexture(cGetItemIcon(itemId)) --   C_Item.GetItemIconByID不需要先缓存，C_Item.GetItemInfo需要先缓存
                if lgnore then
                    Frame1.lgnoreBtn:SetText("恢复")
                else
                    Frame1.lgnoreBtn:SetText("忽略")
                end
                if state == "waiting" then
                    statetext:SetText("等待拍卖")
                    MLframe.CancelBtn:Enable()
                elseif (state == "auctioning") then
                    MLframe.CancelBtn:Enable()
                    if (tonumber(countdownremaining) > 1) then
                        CountDown(index, countdownremaining)
                        if isPaused then
                            timer:Pause()
                            statetext:SetText("暂停中...")
                            MLframe.PauseBtn:SetText("继续")
                        else
                            statetext:SetText("拍卖中...")
                        end
                    end
                elseif state == "success" then
                    statetext:SetText("拍卖成功！")
                    MLframe.CancelBtn:Disable()
                elseif state == "failed" then
                    MLframe.CancelBtn:Enable()
                    statetext:SetText("无人出价，流拍！")
                end
                if bidderlist and (#bidderlist > 0) then --如果有人出价
                    tableSort(bidderlist)
                    local isSelf = false
                    local bidamountText = "有效出价："
                    local bidderText = "有效出价者："
                    for i = 1, math.min(itemCount, #bidderlist) do
                        if bidderlist[i]["bidder"] == UnitName("player") then
                            isSelf = true
                        end
                        if i == math.min(itemCount, #bidderlist) then
                            bidamountText = bidamountText .. "|cffffd60c" .. bidderlist[i].bidamount .. "|rg"
                            bidderText = bidderText .. "|cffffd60c" .. bidderlist[i].bidder .. "|r"
                        else
                            bidamountText = bidamountText .. "|cffffd60c" .. bidderlist[i].bidamount .. "|rg，"
                            bidderText = bidderText .. "|cffffd60c" .. bidderlist[i].bidder .. "|r，"
                        end
                    end
                    curbidamounttext:SetText(bidamountText)
                    if isSelf then
                        curbiddertext:SetText("|cffffd60c你是有效出价者！|r")
                    else
                        curbiddertext:SetText(bidderText)
                    end
                    
                else
                    curbidamounttext:SetText("有效出价：")
                    curbiddertext:SetText("当前无人出价！")
                end
            end
            ItemAuctionFrame:UpdateItemAuctionFrame()
            t[v] = ItemAuctionFrame
            return ItemAuctionFrame
        end
    })
    --只负责调整尺寸
    function AuctionFrame:Update()
        for _, f in ipairs(self.entries) do f:Hide() end
        local height = 0
        if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
            for num, data in ipairs(ZL_CURRENT.auctionlist) do
                local f = self.entries[num]
                if ItemAuctionFrameIsShown(data) then
                    f:Show()
                    f:SetPoint("TOPLEFT", content, "TOPLEFT", 0, -height)
                    height = height + f:GetHeight()
                end
            end
        end
        content:SetHeight(height) --设置滚动放置区域高度

        local offsetY = 0
        if (not PlayerIsML()) then
            -- _G["AuctionFrameTab5"]:Hide()
            MLFrame:Hide()
            offsetY = AuctionFrame.AllMinBtn:GetHeight() + 8
        else
            -- _G["AuctionFrameTab5"]:Show()
            MLFrame:Show()
            offsetY = AuctionFrame.histroy:GetHeight() + AuctionFrame.AllMinBtn:GetHeight() + 8
        end
        AuctionFrame.scrollFrame:SetPoint("TOPLEFT", _G["ZLAuctionFrameDialogBG"], "TOPLEFT", 3, -offsetY)
        AuctionFrame.scrollFrame:SetPoint("BOTTOMRIGHT", _G["ZLAuctionFrameDialogBG"], "BOTTOMRIGHT", -3, 4)
    end
end

--创建显示拍卖主窗口的框架
function ZL:CreateMaxAuctionFrame()
    ZL.maxFrame = CreateFrame("Frame", "AuctionFrameMaxFrame", ZL, "BackdropTemplate") --BackdropTemplateMixin and
    local maxFrame = ZL.maxFrame
    maxFrame:SetPoint("RIGHT", UIParent, "RIGHT", -10, 0)
    maxFrame:SetSize(80, 18)
    maxFrame:SetFrameStrata("DIALOG")
    maxFrame:SetClampedToScreen(true)  --不能超出游戏屏幕，false可以超出游戏屏幕
    maxFrame:SetMovable(true)
    maxFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
    end)
    maxFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    maxFrame.maxBtn = CreateFrame("Button", "AuctionFrameMinmaxBtn", maxFrame, BackdropTemplateMixin and "BackdropTemplate")
    local maxBtn = maxFrame.maxBtn
    maxBtn:SetPoint("RIGHT", maxFrame, "RIGHT")
    maxBtn:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up")
    maxBtn:SetHighlightTexture("Interface\\Buttons\\UI-PlusButton-Hilight")
    maxBtn:SetPushedTexture("Interface\\Buttons\\UI-PlusButton-DOWN")
    maxBtn:SetScript("OnClick", function ()
        maxFrame:Hide()
        ZL.AuctionFrame:Show()
    end)
    maxFrame.fontString = maxFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    maxFrame.fontString:SetPoint("RIGHT", maxBtn, "LEFT", 0, 0)
    maxFrame.fontString:SetText("拍卖清单")
    maxBtn:SetSize(15, maxFrame.fontString:GetHeight())
    maxFrame:SetScript("OnUpdate", function (self)
        local curAuctionList = ZL_CURRENT.auctionlist
        local count = 0
        if curAuctionList and #curAuctionList >= 1 then
            for _, data in ipairs(curAuctionList) do
                if (data.state == "auctioning") and (not data.lgnore) then
                    count = count + 1
                end
            end
        end
        -- print(count)
        if count == 0 then
            maxFrame.fontString:SetText("拍卖清单")
        else
            maxFrame.fontString:SetText("拍卖清单|cffffffff[" .. count .. "]|r")
        end
    end)
end

--创建显示交易剩余时间窗口
function ZL:CreateRemainingTradeTimeFrame()
    ZL.RemainingTradeTimeFrame = CreateFrame("Frame", "RemainingTradeTimeFrame", self)
    local RemainingTradeTimeFrame = ZL.RemainingTradeTimeFrame
    RemainingTradeTimeFrame:SetSize(200, 50)
    RemainingTradeTimeFrame:SetPoint("CENTER")
    RemainingTradeTimeFrame:SetClampedToScreen(true)
    RemainingTradeTimeFrame:SetFrameStrata("HIGH")
    RemainingTradeTimeFrame:SetMovable(true)
    RemainingTradeTimeFrame:SetScript("OnMouseDown", function(self) self:StartMoving() end)
    RemainingTradeTimeFrame:SetScript("OnMouseUp", function(self) self:StopMovingOrSizing() end)
    
    RemainingTradeTimeFrame.RemainingTradeTimeText = RemainingTradeTimeFrame:CreateFontString()
    local RemainingTradeTimeText = RemainingTradeTimeFrame.RemainingTradeTimeText
    RemainingTradeTimeText:SetFontObject(GameFontHighlightLarge)
    RemainingTradeTimeText:SetPoint("TOPLEFT", RemainingTradeTimeFrame, "TOPLEFT")
    RemainingTradeTimeText:SetFont(GameFontNormal:GetFont(), 12)
    RemainingTradeTimeText:SetWordWrap(true)
    RemainingTradeTimeText:SetJustifyH("LEFT")

    if ZL.AuctionFrame.RemainingTradeTimeBtn:GetChecked() then
        RemainingTradeTimeFrame:Show()
        ZL.GetRemainingTradeTime()
        ZL.UpdateRemainingTradeTime =  C_Timer.NewTicker(30, function ()
            ZL.GetRemainingTradeTime()
        end)
    else
        RemainingTradeTimeFrame:Hide()
        if ZL.UpdateRemainingTradeTime then
            ZL.UpdateRemainingTradeTime:Cancel()
        end
    end
   
end
--创建物品拍卖设置框架
function ZL:CreateItemSettingFrame()
    ZL.ItemSettingFrame = CreateFrame("Frame", "ItemSettingFrame", ZL, "UIPanelDialogTemplate")
    local ItemSettingFrame = ZL.ItemSettingFrame
    ItemSettingFrame:SetSize(325, 350)
    ItemSettingFrame:SetPoint("CENTER", UIParent, "CENTER")
    ItemSettingFrame:SetFrameStrata("HIGH")
    ItemSettingFrame:SetClampedToScreen(true)  --不能超出游戏屏幕，false可以超出游戏屏幕
    ItemSettingFrame:SetMovable(true)
    ItemSettingFrame:SetHitRectInsets(0, 0, 0, ItemSettingFrameDialogBG:GetHeight()+3) --设置鼠标可点击区域
    ItemSettingFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
    end)
    ItemSettingFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    ItemSettingFrame:SetScript("OnShow", function (self)
        self.itemIdFrame:Update()
        self.itemLevelFrame:Update()
        self.filterFrame:Update()
    end)
    if WOW_PROJECT_ID ~= 1 then
        _G["ItemSettingFrameClose"]:ClearAllPoints()
        _G["ItemSettingFrameClose"]:SetPoint("TOPRIGHT", ItemSettingFrame, "TOPRIGHT", 2, 1)
    end
    _G["ItemSettingFrameClose"]:HookScript("OnClick", function ()
        LibStub("AceConfigDialog-3.0"):Open("金团自动拍卖助手")
    end)
    ItemSettingFrame.Title:SetText("物品拍卖设置")
    ItemSettingFrame:Hide()

    ItemSettingFrame.itemIdFrame = CreateFrame("Frame", nil, ItemSettingFrame)
    local itemIdFrame = ItemSettingFrame.itemIdFrame
    itemIdFrame:SetPoint("TOPLEFT", ItemSettingFrameDialogBG, "TOPLEFT")
    itemIdFrame:SetSize(ItemSettingFrameDialogBG:GetWidth(), 50)
    
    itemIdFrame.itemIdEditbox = CreateFrame("EditBox", "itemIdFrameitemIdEditbox", itemIdFrame, "InputBoxTemplate")
    local itemIdEditbox = itemIdFrame.itemIdEditbox
    itemIdEditbox:SetPoint("TOPLEFT", itemIdFrame, "TOPLEFT", 28, -5)
    itemIdEditbox:SetSize(50, 20)
    itemIdEditbox:SetAutoFocus(false)
    itemIdEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    itemIdEditbox:SetNumeric(true)
    itemIdEditbox:SetScript("OnEnterPressed", function ()
        itemIdFrame.SerchBtn:Click()
    end)
    itemIdEditbox:SetScript("OnMouseUp", function (self)
        if (select(1, GetCursorInfo())) == "item" then
            self:SetText(select(2, GetCursorInfo()))
            ClearCursor()
        end
    end)
    itemIdFrame.itemIdFont = itemIdFrame:CreateFontString()
    local itemIdFont = itemIdFrame.itemIdFont
    itemIdFont:SetPoint("TOP", itemIdEditbox, "BOTTOM", -2, -5)
    itemIdFont:SetFont(GameFontNormal:GetFont(), 12)
    itemIdFont:SetTextColor(1, 0.82, 0)
    itemIdFont:SetText("物品ID")
    itemIdFont:SetWordWrap(false)
    itemIdFont:SetJustifyH("LEFT")

    itemIdFrame.startBidEditbox = CreateFrame("EditBox", "itemIdFramestartBidEditbox", itemIdFrame, "InputBoxTemplate")
    local startBidEditbox = itemIdFrame.startBidEditbox
    startBidEditbox:SetPoint("LEFT", itemIdEditbox, "RIGHT", 10, 0)
    startBidEditbox:SetSize(45, 20)
    startBidEditbox:SetAutoFocus(false)
    startBidEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    startBidEditbox:SetNumeric(true)
    itemIdFrame.startBidFont = itemIdFrame:CreateFontString()
    local startBidFont = itemIdFrame.startBidFont
    startBidFont:SetPoint("TOP", startBidEditbox, "BOTTOM", -2, -5)
    startBidFont:SetFont(GameFontNormal:GetFont(), 12)
    startBidFont:SetTextColor(1, 0.82, 0)
    startBidFont:SetText("起拍价")
    startBidFont:SetWordWrap(false)
    startBidFont:SetJustifyH("LEFT")

    itemIdFrame.incrementEditbox = CreateFrame("EditBox", "itemIdFrameincrementEditbox", itemIdFrame, "InputBoxTemplate")
    local incrementEditbox = itemIdFrame.incrementEditbox
    incrementEditbox:SetPoint("LEFT", startBidEditbox, "RIGHT", 9, 0)
    incrementEditbox:SetSize(30, 20)
    incrementEditbox:SetAutoFocus(false)
    incrementEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    incrementEditbox:SetNumeric(true)
    itemIdFrame.incrementFont = itemIdFrame:CreateFontString()
    local incrementFont = itemIdFrame.incrementFont
    incrementFont:SetPoint("TOP", incrementEditbox, "BOTTOM", -2, -5)
    incrementFont:SetFont(GameFontNormal:GetFont(), 12)
    incrementFont:SetTextColor(1, 0.82, 0)
    incrementFont:SetText("加价")
    incrementFont:SetWordWrap(false)
    incrementFont:SetJustifyH("LEFT")

    itemIdFrame.itemNameFont = itemIdFrame:CreateFontString()
    local itemNameFont = itemIdFrame.itemNameFont
    itemNameFont:SetPoint("LEFT", incrementFont, "RIGHT", 15, 0)
    itemNameFont:SetFont(GameFontNormal:GetFont(), 12)
    itemNameFont:SetTextColor(1, 0.82, 0)
    itemNameFont:SetText("名称")
    itemNameFont:SetWordWrap(false)
    itemNameFont:SetJustifyH("LEFT")

    itemIdFrame.AddBtn = CreateButton(nil, itemIdFrame, "添加", "LEFT", incrementEditbox, "RIGHT", 5, 0, 40)
    itemIdFrame.AddBtn:SetScript("OnClick", function ()
        local itemId = itemIdEditbox:GetNumber() or 0
        local startbid = startBidEditbox:GetNumber() or 0
        local increment = incrementEditbox:GetNumber() or 0
        if (itemId > 0) and (startbid > 0) and (increment > 0) then
            local isExist = false
            for index, data in ipairs(ZL_SETTING.itemIdSetting) do
                if data.itemId == itemId then
                    isExist = true
                    ZL_SETTING.itemIdSetting[index].startbid = startbid
                    ZL_SETTING.itemIdSetting[index].increment = increment
                end
            end
            if isExist then
                for _, f in ipairs(itemIdFrame.entries) do
                    f:Hide()
                end
                local f = itemIdFrame.entries[1]
                f:Show()
                f:SetValues(itemId, startbid, increment, select(2, cGetItemInfo(itemId)))
                print(Prefix("物品ID已存在！起拍价和每次最低出价已更新！"))
            else
                local itemlink = select(2, cGetItemInfo(itemId))
                if itemlink then
                    table.insert(ZL_SETTING.itemIdSetting, {itemId=itemId, startbid=startbid, increment=increment, itemlink=itemlink})
                    itemIdFrame:Update()
                else
                    print(Prefix("未查询到物品ID信息，请核实填写是否正确！"))
                end
            end
            itemIdEditbox:SetText("")
            startBidEditbox:SetText("")
            incrementEditbox:SetText("")
        else
            print(Prefix("信息填写不完整！"))
            GameTooltipShow(self, "BOTTOM", "TOP")
            GameTooltip:AddLine("信息填写不完整！")
            GameTooltip:Show()
            C_Timer.After(3, function ()
                GameTooltip:Hide()
            end)
        end
    end)
    itemIdFrame.AddBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
        GameTooltip:AddLine("添加物品的三种方式：")
        GameTooltip:AddLine("1、直接输入物品ID，起拍价和加价，按\"添加\"按钮；", 1, 1, 1, false)
        GameTooltip:AddLine("2、鼠标点击物品到\"物品ID\"输入框，自动获取物品ID，\n     然后输入起拍价和加价，按\"添加\"按钮；", 1, 1, 1, false)
        GameTooltip:AddLine("3、鼠标点击物品到已存在物品的图标上，自动替换为\n     新的物品ID，保留原起拍价和加价。", 1, 1, 1, false)
        GameTooltip:Show()
    end)
    itemIdFrame.AddBtn:SetScript("OnLeave", function () GameTooltip:Hide() end)
    itemIdFrame.SerchBtn = CreateButton(nil, itemIdFrame, "搜索", "LEFT", itemIdFrame.AddBtn, "RIGHT", 0, 0, 40)
    itemIdFrame.SerchBtn:SetScript("OnClick", function ()
        local itemId = itemIdEditbox:GetNumber() or 0
        if itemId > 0 then
            local isExist = false
            local startbid, increment, itemlink
            for _, data in ipairs(ZL_SETTING.itemIdSetting) do
                if data.itemId == itemId then
                    isExist = true
                    startbid = data.startbid
                    increment = data.increment
                    itemlink = data.itemlink
                end
            end
            if isExist then
                for _, f in ipairs(itemIdFrame.entries) do f:Hide() end
                local f = itemIdFrame.entries[1]
                f:Show()
                f:SetValues(itemId, startbid, increment, itemlink)
            else
                print(Prefix("物品ID不存在！"))
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("物品ID不存在！")
                GameTooltip:Show()
                C_Timer.After(3, function ()
                    GameTooltip:Hide()
                end)
            end
        else
            itemIdFrame:Update()
        end
    end)
    itemIdFrame.SerchBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
        GameTooltip:AddLine("物品ID如果为空，则展示所有存在的；否则只展示输入的物品ID！", 1, 1, 1, true)
        GameTooltip:Show()
    end)
    itemIdFrame.SerchBtn:SetScript("OnLeave", function () GameTooltip:Hide() end)
    --设置TAB事件
    do
        local editboxList = {"itemIdFrameitemIdEditbox", "itemIdFramestartBidEditbox", "itemIdFrameincrementEditbox"}
        local function OnTabPressed(self)
            EditBox_HandleTabbing(self, editboxList)
        end
        itemIdEditbox:SetScript("OnTabPressed", OnTabPressed)
        startBidEditbox:SetScript("OnTabPressed", OnTabPressed)
        incrementEditbox:SetScript("OnTabPressed", function (self)
            local itemId = itemIdEditbox:GetNumber() or 0
            local startbid = startBidEditbox:GetNumber() or 0
            local increment = incrementEditbox:GetNumber() or 0
            if (itemId > 0) and (startbid > 0) and (increment > 0) then
                itemIdFrame.AddBtn:Click()
            else
                OnTabPressed(self)
            end
        end)
    end
    ItemSettingFrame.itemLevelFrame = CreateFrame("Frame", nil, ItemSettingFrame)
    local itemLevelFrame = ItemSettingFrame.itemLevelFrame
    itemLevelFrame:SetPoint("TOPLEFT", ItemSettingFrameDialogBG, "TOPLEFT")
    itemLevelFrame:SetSize(ItemSettingFrameDialogBG:GetWidth(), 50)

    itemLevelFrame.minLevelEditbox = CreateFrame("EditBox", "itemLevelFrameminLevelEditbox", itemLevelFrame, "InputBoxTemplate")
    local minLevelEditbox = itemLevelFrame.minLevelEditbox
    minLevelEditbox:SetPoint("TOPLEFT", itemLevelFrame, "TOPLEFT", 10, -5)
    minLevelEditbox:SetSize(35, 20)
    minLevelEditbox:SetAutoFocus(false)
    minLevelEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    minLevelEditbox:SetNumeric(true)

    itemLevelFrame.minLevelEditbox.linefont = itemLevelFrame.minLevelEditbox:CreateFontString()
    local linefont = itemLevelFrame.minLevelEditbox.linefont
    linefont:SetPoint("LEFT", minLevelEditbox, "RIGHT", 2, 0)
    linefont:SetFont(GameFontNormal:GetFont(), 12)
    linefont:SetTextColor(1, 0.82, 0)
    linefont:SetText("-")
    linefont:SetWordWrap(false)
    linefont:SetJustifyH("CENTER")

    itemLevelFrame.minLevelFont = itemLevelFrame:CreateFontString()
    local minLevelFont = itemLevelFrame.minLevelFont
    minLevelFont:SetPoint("TOP", minLevelEditbox, "BOTTOM", -2, -5)
    minLevelFont:SetFont(GameFontNormal:GetFont(), 12)
    minLevelFont:SetTextColor(1, 0.82, 0)
    minLevelFont:SetText("最小")
    minLevelFont:SetWordWrap(false)
    minLevelFont:SetJustifyH("LEFT")

    itemLevelFrame.maxLevelEditbox = CreateFrame("EditBox", "itemLevelFramemaxLevelEditbox", itemLevelFrame, "InputBoxTemplate")
    local maxLevelEditbox = itemLevelFrame.maxLevelEditbox
    maxLevelEditbox:SetPoint("LEFT", linefont, "RIGHT", 8, 0)
    maxLevelEditbox:SetSize(35, 20)
    maxLevelEditbox:SetAutoFocus(false)
    maxLevelEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    maxLevelEditbox:SetNumeric(true)
    itemLevelFrame.maxLevelFont = itemLevelFrame:CreateFontString()
    local maxLevelFont = itemLevelFrame.maxLevelFont
    maxLevelFont:SetPoint("TOP", maxLevelEditbox, "BOTTOM", -2, -5)
    maxLevelFont:SetFont(GameFontNormal:GetFont(), 12)
    maxLevelFont:SetTextColor(1, 0.82, 0)
    maxLevelFont:SetText("最大")
    maxLevelFont:SetWordWrap(false)
    maxLevelFont:SetJustifyH("LEFT")

    itemLevelFrame.startBidEditbox = CreateFrame("EditBox", "itemLevelFramestartBidEditbox", itemLevelFrame, "InputBoxTemplate")
    local startBidEditbox = itemLevelFrame.startBidEditbox
    startBidEditbox:SetPoint("LEFT", maxLevelEditbox, "RIGHT", 10, 0)
    startBidEditbox:SetSize(60, 20)
    startBidEditbox:SetAutoFocus(false)
    startBidEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    startBidEditbox:SetNumeric(true)
    itemLevelFrame.startBidFont = itemLevelFrame:CreateFontString()
    local startBidFont = itemLevelFrame.startBidFont
    startBidFont:SetPoint("TOP", startBidEditbox, "BOTTOM", -2, -5)
    startBidFont:SetFont(GameFontNormal:GetFont(), 12)
    startBidFont:SetTextColor(1, 0.82, 0)
    startBidFont:SetText("起拍价")
    startBidFont:SetWordWrap(false)
    startBidFont:SetJustifyH("LEFT")

    itemLevelFrame.incrementEditbox = CreateFrame("EditBox", "itemLevelFrameincrementEditbox", itemLevelFrame, "InputBoxTemplate")
    local incrementEditbox = itemLevelFrame.incrementEditbox
    incrementEditbox:SetPoint("LEFT", startBidEditbox, "RIGHT", 10, 0)
    incrementEditbox:SetSize(60, 20)
    incrementEditbox:SetAutoFocus(false)
    incrementEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    incrementEditbox:SetNumeric(true)
    itemLevelFrame.incrementFont = itemLevelFrame:CreateFontString()
    local incrementFont = itemLevelFrame.incrementFont
    incrementFont:SetPoint("TOP", incrementEditbox, "BOTTOM", -2, -5)
    incrementFont:SetFont(GameFontNormal:GetFont(), 12)
    incrementFont:SetTextColor(1, 0.82, 0)
    incrementFont:SetText("最低加价")
    incrementFont:SetWordWrap(false)
    incrementFont:SetJustifyH("LEFT")
    itemLevelFrame.AddBtn = CreateButton(nil, itemLevelFrame, "+", "LEFT", incrementEditbox, "RIGHT", 2, 0, 24)
    itemLevelFrame.AddBtn:SetScript("OnClick", function (self)
        local minLevel = minLevelEditbox:GetNumber() or 0
        local maxLevel = maxLevelEditbox:GetNumber() or 0
        local startbid = startBidEditbox:GetNumber() or 0
        local increment = incrementEditbox:GetNumber() or 0
        if minLevel > 0 and maxLevel > 0 and startbid > 0 and increment > 0 then
            if maxLevel >= minLevel then
                for _, d in ipairs(ZL_SETTING["itemLevelSetting"]) do
                    if ((d.minLevel <= minLevel) and (d.maxLevel >= minLevel)) or ((d.minLevel <= maxLevel) and (d.maxLevel >= maxLevel)) then
                        GameTooltipShow(self, "LEFT", "RIGHT")
                        GameTooltip:AddLine("警告")
                        GameTooltip:AddLine("装等存在重叠范围，请修改！", 1, 1, 1)
                        GameTooltip:Show()
                        C_Timer.After(2, function ()
                            GameTooltip:Hide()
                        end)
                        return
                    end
                end
                table.insert(ZL_SETTING["itemLevelSetting"], {minLevel=minLevel, maxLevel=maxLevel, startbid=startbid, increment=increment})
                table.sort(ZL_SETTING["itemLevelSetting"], function (a, b)
                    return a.minLevel < b.minLevel
                end)
                itemLevelFrame:Update()
                minLevelEditbox:SetText("")
                maxLevelEditbox:SetText("")
                startBidEditbox:SetText("")
                incrementEditbox:SetText("")
            else
                GameTooltipShow(self, "LEFT", "RIGHT")
                GameTooltip:AddLine("错误")
                GameTooltip:AddLine("最大装等不能小于最小装等！", 1, 1, 1)
                GameTooltip:Show()
                C_Timer.After(2, function ()
                    GameTooltip:Hide()
                end)
            end
        else
            GameTooltipShow(self, "LEFT", "RIGHT")
            GameTooltip:AddLine("错误")
            GameTooltip:AddLine("请输入大于0的数！", 1, 1, 1)
            GameTooltip:Show()
            C_Timer.After(2, function ()
                GameTooltip:Hide()
            end)
        end
    end)
    itemLevelFrame.AddBtn:SetScript("onLeave", function ()
        GameTooltip:Hide()
    end)
    itemLevelFrame:Hide()
    --设置TAB事件
    do
        local editboxList = {"itemLevelFrameminLevelEditbox", "itemLevelFramemaxLevelEditbox", "itemLevelFramestartBidEditbox", "itemLevelFrameincrementEditbox"}
        local function OnTabPressed(self)
            EditBox_HandleTabbing(self, editboxList)
        end
        minLevelEditbox:SetScript("OnTabPressed", OnTabPressed)
        maxLevelEditbox:SetScript("OnTabPressed", OnTabPressed)
        startBidEditbox:SetScript("OnTabPressed", OnTabPressed)
        incrementEditbox:SetScript("OnTabPressed", OnTabPressed)
    end

    ItemSettingFrame.filterFrame = CreateFrame("Frame", nil, ItemSettingFrame)
    local filterFrame = ItemSettingFrame.filterFrame
    filterFrame:SetPoint("TOPLEFT", ItemSettingFrameDialogBG, "TOPLEFT")
    filterFrame:SetSize(ItemSettingFrameDialogBG:GetWidth(), 50)
    
    filterFrame.filterItemIdEditbox = CreateFrame("EditBox", "itemIdFrameitemIdEditbox", filterFrame, "InputBoxTemplate")
    local filterItemIdEditbox = filterFrame.filterItemIdEditbox
    filterItemIdEditbox:SetPoint("TOPLEFT", filterFrame, "TOPLEFT", 31, -5)
    filterItemIdEditbox:SetSize(100, 20)
    filterItemIdEditbox:SetAutoFocus(false)
    filterItemIdEditbox:SetFont(GameFontNormal:GetFont(), 12, "")
    filterItemIdEditbox:SetNumeric(true)
    filterItemIdEditbox:SetScript("OnEnterPressed", function ()
        filterFrame.AddBtn:Click()
    end)
    filterItemIdEditbox:SetScript("OnMouseUp", function (self)
        if (select(1, GetCursorInfo())) == "item" then
            self:SetText(select(2, GetCursorInfo()))
            ClearCursor()
        end
    end)

    filterFrame.AddBtn = CreateButton(nil, filterFrame, "添加", "LEFT", filterItemIdEditbox, "RIGHT", 5, 0, 40)
    filterFrame.AddBtn:SetScript("OnClick", function ()
        local itemId = filterItemIdEditbox:GetNumber() or 0
        if (itemId > 0) then
            local isExist = false
            for _, data in ipairs(ZL_SETTING.filterItemId) do
                if data.itemId == itemId then
                    isExist = true
                end
            end
            if isExist then
                for _, f in ipairs(filterFrame.entries) do
                    f:Hide()
                end
                local f = filterFrame.entries[1]
                f:Show()
                f:SetValues(itemId, select(2, cGetItemInfo(itemId)))
                print(Prefix("物品ID已存在！"))
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("物品ID已存在！！")
                GameTooltip:Show()
                C_Timer.After(3, function ()
                    GameTooltip:Hide()
                end)
            else
                local itemlink = select(2, cGetItemInfo(itemId))
                if itemlink then
                    table.insert(ZL_SETTING.filterItemId, {itemId=itemId, itemlink=itemlink})
                    filterFrame:Update()
                else
                    print(Prefix("未查询到物品ID信息，请核实填写是否正确！"))
                    GameTooltipShow(self, "BOTTOM", "TOP")
                    GameTooltip:AddLine("未查询到物品ID信息，请核实填写是否正确！")
                    GameTooltip:Show()
                    C_Timer.After(3, function ()
                        GameTooltip:Hide()
                    end)
                end
            end
            filterItemIdEditbox:SetText("")
        else
            print(Prefix("信息填写不完整！"))
            GameTooltipShow(self, "BOTTOM", "TOP")
            GameTooltip:AddLine("信息填写不完整！")
            GameTooltip:Show()
            C_Timer.After(3, function ()
                GameTooltip:Hide()
            end)
        end
    end)
    filterFrame.AddBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
        GameTooltip:AddLine("添加物品的三种方式：")
        GameTooltip:AddLine("1、直接输入物品ID，按\"添加\"按钮；", 1, 1, 1, false)
        GameTooltip:AddLine("2、鼠标点击物品到\"物品ID\"输入框，自动获取物品ID，\n     按\"添加\"按钮；", 1, 1, 1, false)
        GameTooltip:AddLine("3、鼠标点击物品到已存在物品的图标上，自动替换为\n     新的物品ID", 1, 1, 1, false)
        GameTooltip:Show()
    end)
    filterFrame.AddBtn:SetScript("OnLeave", function () GameTooltip:Hide() end)
    filterFrame.SerchBtn = CreateButton(nil, filterFrame, "搜索", "LEFT", filterFrame.AddBtn, "RIGHT", 0, 0, 40)
    filterFrame.SerchBtn:SetScript("OnClick", function ()
        local itemId = filterItemIdEditbox:GetNumber() or 0
        if itemId > 0 then
            local isExist = false
            local itemlink
            for _, data in ipairs(ZL_SETTING.filterItemId) do
                if data.itemId == itemId then
                    isExist = true
                    itemlink = data.itemlink
                end
            end
            if isExist then
                for _, f in ipairs(filterFrame.entries) do f:Hide() end
                local f = filterFrame.entries[1]
                f:Show()
                f:SetValues(itemId, itemlink)
            else
                print(Prefix("物品ID不存在！"))
                GameTooltipShow(self, "BOTTOM", "TOP")
                GameTooltip:AddLine("物品ID不存在！")
                GameTooltip:Show()
                C_Timer.After(3, function ()
                    GameTooltip:Hide()
                end)
            end
        else
            filterFrame:Update()
        end
    end)
    filterFrame.SerchBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "TOPLEFT", "BOTTOMRIGHT")
        GameTooltip:AddLine("物品ID如果为空，则展示所有存在的；否则只展示输入的物品ID！", 1, 1, 1, true)
        GameTooltip:Show()
    end)
    filterFrame.SerchBtn:SetScript("OnLeave", function () GameTooltip:Hide() end)

    filterFrame.filterItemIdFont = filterFrame:CreateFontString()
    local filterItemIdFont = filterFrame.filterItemIdFont
    filterItemIdFont:SetPoint("TOPLEFT", filterItemIdEditbox, "BOTTOMLEFT", 12, -5)
    filterItemIdFont:SetFont(GameFontNormal:GetFont(), 12)
    filterItemIdFont:SetTextColor(1, 0.82, 0)
    filterItemIdFont:SetText("物品ID")
    filterItemIdFont:SetWordWrap(false)
    filterItemIdFont:SetJustifyH("LEFT")

    filterFrame.filterItemNameFont = filterFrame:CreateFontString()
    local filterItemNameFont = filterFrame.filterItemNameFont
    filterItemNameFont:SetPoint("LEFT", filterItemIdFont, "RIGHT", 50, 0)
    filterItemNameFont:SetFont(GameFontNormal:GetFont(), 12)
    filterItemNameFont:SetTextColor(1, 0.82, 0)
    filterItemNameFont:SetText("名称")
    filterItemNameFont:SetWordWrap(false)
    filterItemNameFont:SetJustifyH("LEFT")
    filterFrame:Hide()


    --创建滚动条
    ItemSettingFrame.scrollFrame = CreateFrame("ScrollFrame", nil, ItemSettingFrame, "UIPanelScrollFrameTemplate")
    ItemSettingFrame.scrollFrame:SetPoint("TOPLEFT", _G["ItemSettingFrameDialogBG"], "TOPLEFT", 3, -50)
    ItemSettingFrame.scrollFrame:SetPoint("BOTTOMRIGHT", _G["ItemSettingFrameDialogBG"], "BOTTOMRIGHT", -3, 4)
    ItemSettingFrame.scrollFrame:SetClipsChildren(true) --必须设置为true，scrollFrame所有的子元素才会被剪切
    ItemSettingFrame.scrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel) --重设滑动条鼠标滚轮事件
    --重设ScrollBar位置，放置到scrollFrame内，防止被剪切掉
    ItemSettingFrame.scrollFrame.ScrollBar:ClearAllPoints()
    ItemSettingFrame.scrollFrame.ScrollBar:SetPoint("TOPLEFT", ItemSettingFrame.scrollFrame, "TOPRIGHT", -10, -15)
    ItemSettingFrame.scrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", ItemSettingFrame.scrollFrame, "BOTTOMRIGHT", -5, 15)

    local function Tab_OnClick(self)
        local frame = self:GetParent()
        local tabId = self:GetID()
        if tabId == 1 then
            itemIdFrame:Show()
            itemLevelFrame:Hide()
            filterFrame:Hide()
        elseif tabId == 2 then
            itemIdFrame:Hide()
            itemLevelFrame:Show()
            filterFrame:Hide()
        elseif tabId == 3 then
            itemIdFrame:Hide()
            itemLevelFrame:Hide()
            filterFrame:Show()
        end
        PanelTemplates_SetTab(frame, tabId)
        local scrollchild = frame.scrollFrame:GetScrollChild()
        if scrollchild then
            scrollchild:Hide()
        end
        frame.scrollFrame:SetScrollChild(self.content)
        self.content:Show()
    end

    local function CreateTab(frame, numTabs, ...)
        frame.numTabs = numTabs
        local contents = {}
        local frameName = frame:GetName()
        local template = ""
        for i = 1, numTabs do
            if WOW_PROJECT_ID == 1 then
                template = "PanelTabButtonTemplate"
            elseif WOW_PROJECT_ID == 11 then
                template = "CharacterFrameTabButtonTemplate"
            end
            local tab = CreateFrame("Button", frameName.."Tab"..i, frame, template)
            tab:SetID(i)
            tab:SetText(select(i, ...))
            tab:SetScript("OnClick", Tab_OnClick)
            if WOW_PROJECT_ID == 1 then
                if i ==1 then
                    tab:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 5, 7)
                else
                    tab:SetPoint("TOPLEFT", _G[frameName.."Tab"..(i-1)], "TOPRIGHT", 1, 0)
                end
            elseif WOW_PROJECT_ID == 11 then
                if i ==1 then
                    tab:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 0, 5)
                else
                    tab:SetPoint("TOPLEFT", _G[frameName.."Tab"..(i-1)], "TOPRIGHT", -20, 0)
                end
            end
            tab.content = CreateFrame("Frame", nil, frame.scrollFrame)
            tab.content:SetPoint("TOPLEFT", frame.scrollFrame, "TOPLEFT")
            tab.content:SetSize(frame.scrollFrame:GetWidth() - 40, 600)
            tab.content:Hide()
            table.insert(contents, tab.content)
        end
        Tab_OnClick(_G[frameName.."Tab1"])
        return unpack(contents)
    end

    local itemIdContent, itemLevelContent, itemFilterContent = CreateTab(ItemSettingFrame, 3, "按物品", "按装等", "过滤")
    
    itemIdFrame.entries = setmetatable({}, {
        __index = function(t, v)
            local f = CreateFrame("Frame", nil, itemIdContent)
            if v > 1 then
                f:SetPoint("TOPLEFT", t[v - 1], "BOTTOMLEFT", 0, -8)
                f:SetPoint("TOPRIGHT", t[v - 1], "BOTTOMRIGHT", 0, -8)
            else
                f:SetPoint("TOPLEFT", itemIdContent, "TOPLEFT", 0, -5)
                f:SetPoint("TOPRIGHT", itemIdContent, "TOPRIGHT", 0, -5)
            end
            f:SetHeight(15)

            f.itemicon = CreateFrame("Button", nil, f)
            f.itemicon:SetSize(18, 18)
            f.itemicon:EnableMouse(true)
            f.itemicon:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
            f.itemicon:SetPoint("LEFT", f, "LEFT", 2, 0)
            f.itemicon:SetScript("OnEnter", function()
                GameTooltip:ClearAllPoints()
                GameTooltip:ClearLines()
                GameTooltip:SetOwner(f, "ANCHOR_NONE")
                GameTooltip:SetHyperlink("item:" .. f.itemId)
                GameTooltip:SetPoint("RIGHT", f, "LEFT", -5, 0)
                GameTooltip:Show()
            end)
            f.itemicon:SetScript("OnLeave", function() GameTooltip:Hide() end)
            f.itemicon:SetScript("OnMouseUp", function (self)
                if (select(1, GetCursorInfo())) == "item" then
                    local _, itemId, itemlink = GetCursorInfo()
                    local isExist = false
                    for _, data in ipairs(ZL_SETTING.itemIdSetting) do
                        if data.itemId == itemId then
                            isExist = true
                            break
                        end
                    end
                    if (not isExist) then
                        ZL_SETTING.itemIdSetting[v].itemId = itemId
                        ZL_SETTING.itemIdSetting[v].itemlink = itemlink
                        itemIdFrame:Update()
                        ClearCursor()
                    else
                        print(Prefix("物品ID已存在！"))
                        GameTooltipShow(self, "BOTTOM", "TOP")
                        GameTooltip:AddLine("物品ID已存在！")
                        GameTooltip:Show()
                        C_Timer.After(3, function ()
                            GameTooltip:Hide()
                        end)
                    end
                    
                end
            end)

            f.itemIdBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.itemIdBox:SetPoint("LEFT", f.itemicon, "RIGHT", 5, 0)
            f.itemIdBox:SetSize(50, 15)
            f.itemIdBox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.itemIdBox:SetMultiLine(false)
            f.itemIdBox:SetTextColor(1, 1, 1)
            f.itemIdBox:SetJustifyH("LEFT")
            f.itemIdBox:SetAutoFocus(false)
            f.itemIdBox:SetNumeric(true)
            f.itemIdBox:Disable()

            f.startBidBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.startBidBox:SetPoint("LEFT", f.itemIdBox, "RIGHT", 9, 0)
            f.startBidBox:SetSize(45, 15)
            f.startBidBox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.startBidBox:SetMultiLine(false)
            f.startBidBox:SetTextColor(1, 1, 1)
            f.startBidBox:SetJustifyH("RIGHT")
            f.startBidBox:SetAutoFocus(false)
            f.startBidBox:SetNumeric(true)
            f.startBidBox:SetTextInsets(0, 2, 0, 0)
            f.startBidBox:SetScript("OnEnterPressed", function(self)
                ZL_SETTING.itemIdSetting[v].startbid = self:GetNumber() > 0 and self:GetNumber() or ZL_SETTING.itemIdSetting[v].startbid
                self:ClearFocus()
            end)
            f.startBidBox:SetScript("OnEscapePressed", function(self)
                self:SetNumber(ZL_SETTING.itemIdSetting[v].startbid)
                self:ClearFocus()
            end)

            f.incrementBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.incrementBox:SetPoint("LEFT", f.startBidBox, "RIGHT", 9, 0)
            f.incrementBox:SetSize(30, 15)
            f.incrementBox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.incrementBox:SetMultiLine(false)
            f.incrementBox:SetTextColor(1, 1, 1)
            f.incrementBox:SetJustifyH("RIGHT")
            f.incrementBox:SetAutoFocus(false)
            f.incrementBox:SetNumeric(true)
            f.incrementBox:SetTextInsets(0, 2, 0, 0)
            f.incrementBox:SetScript("OnEnterPressed", function(self)
                ZL_SETTING.itemIdSetting[v].increment = self:GetNumber() > 0 and self:GetNumber() or ZL_SETTING.itemIdSetting[v].increment
                self:ClearFocus()
            end)
            f.incrementBox:SetScript("OnEscapePressed", function(self)
                self:SetNumber(ZL_SETTING.itemIdSetting[v].increment)
                self:ClearFocus()
            end)

            f.itemNameFont = f:CreateFontString(nil, "BACKGROUND")
            f.itemNameFont:SetPoint("LEFT", f.incrementBox, "RIGHT", 5, 0)
            f.itemNameFont:SetSize(92, 15)
            f.itemNameFont:SetFont(GameFontNormal:GetFont(), 12)
            f.itemNameFont:SetTextColor(1, 1, 1)
            f.itemNameFont:SetWordWrap(false)
            f.itemNameFont:SetJustifyH("LEFT")

            f.del = CreateButton(nil, f, "-", "LEFT", f.itemNameFont, "RIGHT", 2, 0, 20, 20)
            f.del:SetScript("OnClick", function (self)
                table.remove(ZL_SETTING.itemIdSetting, v)
                itemIdFrame:Update()
            end)
            function f:SetValues(itemId, startbid, increment, itemlink)
                self.itemicon:SetNormalTexture(cGetItemIcon(itemId))
				self.itemIdBox:SetNumber(itemId)
                self.startBidBox:SetNumber(startbid)
                self.incrementBox:SetNumber(increment)
                self.itemNameFont:SetText(itemlink)
                local textwidth = math.floor(self.itemNameFont:GetStringWidth()) + 10
                if textwidth > 90 then
                    self.itemNameFont:SetTextScale(92/textwidth)
                end
				self.itemId = itemId
            end
            t[v] = f
            return f
        end
    })
    function itemIdFrame:Update()
        for _, f in ipairs(self.entries) do f:Hide() end
        for num, data in ipairs(ZL_SETTING.itemIdSetting) do
            local f = self.entries[num]
            f:Show()
            f:SetValues(data.itemId, data.startbid, data.increment, data.itemlink)
        end
        itemIdContent:SetHeight(20 * #ZL_SETTING.itemIdSetting - 5)
    end
    
    itemLevelFrame.entries = setmetatable({}, {
        __index = function(t, v)
            local f = CreateFrame("Frame", nil, itemLevelContent)
            if v > 1 then
                f:SetPoint("TOPLEFT", t[v - 1], "BOTTOMLEFT", 0, -8)
                f:SetPoint("TOPRIGHT", t[v - 1], "BOTTOMRIGHT", 0, -8)
            else
                f:SetPoint("TOPLEFT", itemLevelContent, "TOPLEFT", 0, -5)
                f:SetPoint("TOPRIGHT", itemLevelContent, "TOPRIGHT", 0, -5)
            end
            f:SetHeight(15)

            f.minLevelbox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.minLevelbox:SetPoint("TOPLEFT", f, "TOPLEFT", 7, 0)
            f.minLevelbox:SetSize(35, 15)
            f.minLevelbox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.minLevelbox:SetMultiLine(false)
            f.minLevelbox:SetTextColor(1, 1, 1)
            f.minLevelbox:SetJustifyH("LEFT")
            f.minLevelbox:SetAutoFocus(false)
            f.minLevelbox:SetNumeric(true)
            f.minLevelbox:Disable()

            f.minLevelbox.linefont = f.minLevelbox:CreateFontString(nil, "BACKGROUND")
            local linefontf = f.minLevelbox.linefont
            linefontf:SetPoint("LEFT", f.minLevelbox, "RIGHT", 2, 0)
            linefontf:SetFont(GameFontNormal:GetFont(), 12)
            linefontf:SetTextColor(1, 0.82, 0)
            linefontf:SetText("-")
            linefontf:SetWordWrap(false)
            linefontf:SetJustifyH("CENTER")

            f.maxLevelbox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.maxLevelbox:SetPoint("LEFT", linefontf, "RIGHT", 8, 0)
            f.maxLevelbox:SetSize(35, 15)
            f.maxLevelbox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.maxLevelbox:SetMultiLine(false)
            f.maxLevelbox:SetTextColor(1, 1, 1)
            f.maxLevelbox:SetJustifyH("LEFT")
            f.maxLevelbox:SetAutoFocus(false)
            f.maxLevelbox:SetNumeric(true)
            f.maxLevelbox:Disable()
            f.startbidbox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.startbidbox:SetPoint("LEFT", f.maxLevelbox, "RIGHT", 10, 0)
            f.startbidbox:SetSize(60, 15)
            f.startbidbox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.startbidbox:SetMultiLine(false)
            f.startbidbox:SetTextColor(1, 1, 1)
            f.startbidbox:SetJustifyH("CENTER")
            f.startbidbox:SetAutoFocus(false)
            f.startbidbox:SetNumeric(true)
            f.startbidbox:SetScript("OnEnterPressed", function(self)
                ZL_SETTING.itemLevelSetting[v].startbid= self:GetNumber() > 0 and self:GetNumber() or ZL_SETTING.itemLevelSetting[v].startbid
                self:ClearFocus()
            end)
            f.startbidbox:SetScript("OnEscapePressed", function(self)
                self:SetNumber(ZL_SETTING.itemLevelSetting[v].startbid)
                self:ClearFocus()
            end)

            f.incrementbox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.incrementbox:SetPoint("LEFT", f.startbidbox, "RIGHT", 10, 0)
            f.incrementbox:SetSize(60, 15)
            f.incrementbox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.incrementbox:SetMultiLine(false)
            f.incrementbox:SetTextColor(1, 1, 1)
            f.incrementbox:SetJustifyH("CENTER")
            f.incrementbox:SetAutoFocus(false)
            f.incrementbox:SetNumeric(true)
            f.incrementbox:SetScript("OnEnterPressed", function(self)
                ZL_SETTING.itemLevelSetting[v].increment = self:GetNumber() > 0 and self:GetNumber() or ZL_SETTING.itemLevelSetting[v].increment
                self:ClearFocus()
            end)
            f.incrementbox:SetScript("OnEscapePressed", function(self)
                self:SetNumber(ZL_SETTING.itemLevelSetting[v].increment)
                self:ClearFocus()
            end)
            f.del = CreateButton(nil, f, "-", "LEFT", f.incrementbox, "RIGHT", 2, 0, 24)
            f.del:SetScript("OnClick", function (self)
                table.remove(ZL_SETTING.itemLevelSetting, v)
                itemLevelFrame:Update()
            end)

            function f:SetValues(minLevel, maxLevel, startbid, increment)
                self.minLevelbox:SetNumber(minLevel)
                self.maxLevelbox:SetNumber(maxLevel)
                self.startbidbox:SetNumber(startbid)
                self.incrementbox:SetNumber(increment)
            end

            t[v] = f
            return f
        end
    })
    function itemLevelFrame:Update()
        for _, f in ipairs(self.entries) do f:Hide() end
        for num, data in ipairs(ZL_SETTING.itemLevelSetting) do
            local f = self.entries[num]
            f:Show()
            f:SetValues(data.minLevel, data.maxLevel, data.startbid, data.increment)
        end
        itemLevelContent:SetHeight(20 * #ZL_SETTING.itemLevelSetting - 5)
    end

    filterFrame.entries = setmetatable({}, {
        __index = function(t, v)
            local f = CreateFrame("Frame", nil, itemFilterContent)
            if v > 1 then
                f:SetPoint("TOPLEFT", t[v - 1], "BOTTOMLEFT", 0, -8)
                f:SetPoint("TOPRIGHT", t[v - 1], "BOTTOMRIGHT", 0, -8)
            else
                f:SetPoint("TOPLEFT", itemFilterContent, "TOPLEFT", 0, -5)
                f:SetPoint("TOPRIGHT", itemFilterContent, "TOPRIGHT", 0, -5)
            end
            f:SetHeight(15)

            f.itemicon = CreateFrame("Button", nil, f)
            f.itemicon:SetSize(18, 18)
            f.itemicon:EnableMouse(true)
            f.itemicon:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
            f.itemicon:SetPoint("LEFT", f, "LEFT", 2, 0)
            f.itemicon:SetScript("OnEnter", function()
                GameTooltip:ClearAllPoints()
                GameTooltip:ClearLines()
                GameTooltip:SetOwner(f, "ANCHOR_NONE")
                GameTooltip:SetHyperlink("item:" .. f.itemId)
                GameTooltip:SetPoint("RIGHT", f, "LEFT", -5, 0)
                GameTooltip:Show()
            end)
            f.itemicon:SetScript("OnLeave", function() GameTooltip:Hide() end)
            f.itemicon:SetScript("OnMouseUp", function (self)
                if (select(1, GetCursorInfo())) == "item" then
                    local _, itemId, itemlink = GetCursorInfo()
                    local isExist = false
                    for _, data in ipairs(ZL_SETTING.filterItemId) do
                        if data.itemId == itemId then
                            isExist = true
                        end
                    end
                    if (not isExist) then
                        ZL_SETTING.filterItemId[v].itemId = itemId
                        ZL_SETTING.filterItemId[v].itemlink = itemlink
                        filterFrame:Update()
                        ClearCursor()
                    else
                        print(Prefix("物品ID已存在！"))
                        GameTooltipShow(self, "BOTTOM", "TOP")
                        GameTooltip:AddLine("物品ID已存在！")
                        GameTooltip:Show()
                        C_Timer.After(3, function ()
                            GameTooltip:Hide()
                        end)
                    end
                    
                end
            end)

            f.itemIdBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.itemIdBox:SetPoint("LEFT", f.itemicon, "RIGHT", 8, 0)
            f.itemIdBox:SetSize(70, 15)
            f.itemIdBox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.itemIdBox:SetMultiLine(false)
            f.itemIdBox:SetTextColor(1, 1, 1)
            f.itemIdBox:SetJustifyH("LEFT")
            f.itemIdBox:SetAutoFocus(false)
            f.itemIdBox:SetNumeric(true)
            f.itemIdBox:Disable()

            f.itemNameFont = f:CreateFontString(nil, "BACKGROUND")
            f.itemNameFont:SetPoint("LEFT", f.itemIdBox, "RIGHT", 5, 0)
            f.itemNameFont:SetSize(150, 15)
            f.itemNameFont:SetFont(GameFontNormal:GetFont(), 12)
            f.itemNameFont:SetTextColor(1, 1, 1)
            f.itemNameFont:SetWordWrap(false)
            f.itemNameFont:SetJustifyH("LEFT")

            f.del = CreateButton(nil, f, "-", "LEFT", f.itemNameFont, "RIGHT", 2, 0, 20, 20)
            f.del:SetScript("OnClick", function (self)
                table.remove(ZL_SETTING.filterItemId, v)
                filterFrame:Update()
            end)
            function f:SetValues(itemId, itemlink)
                self.itemicon:SetNormalTexture(cGetItemIcon(itemId))
				self.itemIdBox:SetNumber(itemId)
                self.itemNameFont:SetText(itemlink)
                local textwidth = math.floor(self.itemNameFont:GetStringWidth()) + 10
                if textwidth > 150 then
                    self.itemNameFont:SetTextScale(92/textwidth)
                end
				self.itemId = itemId
            end
            t[v] = f
            return f
        end
    })
    function filterFrame:Update()
        for _, f in ipairs(self.entries) do f:Hide() end
        for num, data in ipairs(ZL_SETTING.filterItemId) do
            local f = self.entries[num]
            f:Show()
            f:SetValues(data.itemId, data.itemlink)
        end
        itemFilterContent:SetHeight(20 * #ZL_SETTING.filterItemId - 5)
    end
end

--创建历史拍卖记录和当前拍卖收入记录框架
function ZL:CreateAuctionRecordFrame()
    ZL.AuctionRecordFrame = CreateFrame("Frame", "AuctionRecordFrame", ZL, "UIPanelDialogTemplate")
    local AuctionRecordFrame = ZL.AuctionRecordFrame
    AuctionRecordFrame:SetSize(325, 350)
    AuctionRecordFrame:SetPoint("CENTER", UIParent, "CENTER")
    AuctionRecordFrame:SetFrameStrata("HIGH")
    AuctionRecordFrame:SetClampedToScreen(true)  --不能超出游戏屏幕，false可以超出游戏屏幕
    AuctionRecordFrame:SetMovable(true)
    AuctionRecordFrame:SetHitRectInsets(0, 0, 0, AuctionRecordFrameDialogBG:GetHeight()+3) --设置鼠标可点击区域
    AuctionRecordFrame:SetScript("OnMouseUp", function (self)
        self:StopMovingOrSizing()
    end)
    AuctionRecordFrame:SetScript("OnMouseDown", function (self)
        self:StartMoving()
    end)
    AuctionRecordFrame:SetScript("OnShow", function (self)
        self.historyFrame:Update()
        self.currentIncomeFrame:Update()
        self.playerBalanceFrame:Update()
        if PlayerIsML() then
            _G["AuctionRecordFrameTab3"]:Show()
        else
            _G["AuctionRecordFrameTab3"]:Hide()
        end
    end)
    AuctionRecordFrame.Title:SetText("拍卖记录")
    if WOW_PROJECT_ID ~= 1 then
        _G["AuctionRecordFrameClose"]:ClearAllPoints()
        _G["AuctionRecordFrameClose"]:SetPoint("TOPRIGHT", AuctionRecordFrame, "TOPRIGHT", 2, 1)
    end
    AuctionRecordFrame:Hide()

    AuctionRecordFrame.historyFrame = CreateFrame("Frame", nil, AuctionRecordFrame)
    local historyFrame = AuctionRecordFrame.historyFrame
    historyFrame:SetPoint("TOPLEFT", AuctionRecordFrameDialogBG, "TOPLEFT")
    historyFrame:SetSize(AuctionRecordFrameDialogBG:GetWidth(), 50)
    -- background(historyFrame)

    historyFrame.ClearHistoryBtn = CreateButton(nil, historyFrame, "清空历史记录", "TOPLEFT", historyFrame, "TOPLEFT", 5, -5, 100)
    local ClearHistoryBtn = historyFrame.ClearHistoryBtn
    ClearHistoryBtn:SetScript("OnClick", function ()
        StaticPopup_Show("ZL_CLEARHISTORYWARNING")
    end)
    historyFrame.nameFont = historyFrame:CreateFontString()
    local nameFont = historyFrame.nameFont
    nameFont:SetPoint("TOPLEFT", ClearHistoryBtn, "BOTTOMLEFT", 5, -5)
    nameFont:SetFont(GameFontNormal:GetFont(), 12)
    nameFont:SetTextColor(1, 0.82, 0)
    nameFont:SetText("     名称")
    nameFont:SetWordWrap(false)
    nameFont:SetJustifyH("LEFT")

    historyFrame.TotalIncomeFont = historyFrame:CreateFontString()
    local TotalIncomeFont = historyFrame.TotalIncomeFont
    TotalIncomeFont:SetPoint("LEFT", nameFont, "RIGHT", 40, 0)
    TotalIncomeFont:SetFont(GameFontNormal:GetFont(), 12)
    TotalIncomeFont:SetTextColor(1, 0.82, 0)
    TotalIncomeFont:SetText("浄收入(g)")
    TotalIncomeFont:SetWordWrap(false)
    TotalIncomeFont:SetJustifyH("RIGHT")

    historyFrame.auctionDateFont = historyFrame:CreateFontString()
    local auctionDateFont = historyFrame.auctionDateFont
    auctionDateFont:SetPoint("LEFT", TotalIncomeFont, "RIGHT", 30, 0)
    auctionDateFont:SetFont(GameFontNormal:GetFont(), 12)
    auctionDateFont:SetTextColor(1, 0.82, 0)
    auctionDateFont:SetText("创建时间")
    auctionDateFont:SetWordWrap(false)
    auctionDateFont:SetJustifyH("RIGHT")
    historyFrame:Hide()

    AuctionRecordFrame.currentIncomeFrame = CreateFrame("Frame", nil, AuctionRecordFrame)
    local currentIncomeFrame = AuctionRecordFrame.currentIncomeFrame
    currentIncomeFrame:SetPoint("TOPLEFT", AuctionRecordFrameDialogBG, "TOPLEFT")
    currentIncomeFrame:SetSize(AuctionRecordFrameDialogBG:GetWidth(), 50)

    currentIncomeFrame.groupNumbers = currentIncomeFrame:CreateFontString()
    local groupNumbers = currentIncomeFrame.groupNumbers
    groupNumbers:SetPoint("TOPLEFT", currentIncomeFrame, "TOPLEFT", 5, -8)
    groupNumbers:SetFont(GameFontNormal:GetFont(), 12)
    -- groupNumbers:SetTextColor(1, 1, 1)
    groupNumbers:SetText("打工人数:")
    groupNumbers:SetWordWrap(false)
    groupNumbers:SetJustifyH("LEFT")
    currentIncomeFrame.groupNumbersEditBox = CreateFrame("EditBox", nil, currentIncomeFrame, "InputBoxTemplate")
    local groupNumbersEditBox = currentIncomeFrame.groupNumbersEditBox
    groupNumbersEditBox:SetPoint("LEFT", groupNumbers, "RIGHT", 10, 0)
    groupNumbersEditBox:SetSize(30, 15)
    groupNumbersEditBox:SetFont(GameFontNormal:GetFont(), 12, "")
    groupNumbersEditBox:SetMultiLine(false)
    groupNumbersEditBox:SetTextColor(1, 1, 1)
    groupNumbersEditBox:SetJustifyH("LEFT")
    groupNumbersEditBox:SetAutoFocus(false)
    groupNumbersEditBox:SetNumeric(true)
    groupNumbersEditBox:SetScript("OnEnterPressed", function (self)
        self:ClearFocus()
    end)
    groupNumbersEditBox:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "BOTTOM", "TOP", 0, 5)
        GameTooltip:AddLine("不填写将按照全团总人数|cffffd100" .. GetNumGroupMembers() .. "|r人计算", 1, 1, 1)
        GameTooltip:Show()
    end)
    groupNumbersEditBox:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    currentIncomeFrame.SendMsgBtn = CreateButton(nil, currentIncomeFrame, "通报", "LEFT", groupNumbersEditBox, "RIGHT", 0, 0, 40)
    local SendMsgBtn = currentIncomeFrame.SendMsgBtn
    SendMsgBtn:SetScript("OnClick", function ()
        local msgStr = ""
        local totalamount = 0
        local totalincome = 0
        local totalpayout = 0
        local averageamount = 0
        local msglist = {}
        local numGroupMembers
        if currentIncomeFrame.groupNumbersEditBox:GetNumber() and currentIncomeFrame.groupNumbersEditBox:GetNumber() > 0 then
            numGroupMembers = currentIncomeFrame.groupNumbersEditBox:GetNumber()
        else
            numGroupMembers = GetNumGroupMembers()
        end
        if ZL_CURRENT.IncomeList and (#ZL_CURRENT.IncomeList > 0) then
            msgStr = "<<<收支清单>>>"
            table.insert(msglist, msgStr)
            for index, data in ipairs(ZL_CURRENT.IncomeList) do
                msgStr = index .. "、" .. data.notes .. "：" .. data.player .. "(" .. data.amount .. "g)"
                if data.amount > 0 then
                    totalincome = totalincome + data.amount
                else
                    totalpayout = totalpayout + data.amount
                end
                table.insert(msglist, msgStr)
            end
            msgStr = "<<<收支总览>>>"
            table.insert(msglist, msgStr)
            totalamount =totalincome + totalpayout
            msgStr = "总收入：" .. totalincome
            table.insert(msglist, msgStr)
            msgStr = "总支出：" .. (totalpayout == 0 and 0 or -totalpayout)
            table.insert(msglist, msgStr)
            msgStr = "浄收入：" .. totalamount
            table.insert(msglist, msgStr)
            msgStr = "<<<工资总览>>>"
            table.insert(msglist, msgStr)
            msgStr = "打工人数：" .. numGroupMembers .. "人"
            table.insert(msglist, msgStr)
            averageamount = math.floor(totalamount / numGroupMembers)
            ZL_CURRENT["aveWages"] = averageamount
            msgStr = "人均工资：" .. averageamount .. "(已抹零)"
            table.insert(msglist, msgStr)
            msgStr = "<<<小队工资>>>"
            table.insert(msglist, msgStr)
            -- 创建一个表来存储每个小队的成员信息
            local teamInfo = {}
            local amount
            -- 遍历每个团队成员
            for i = 1, GetNumGroupMembers() do
                -- 获取团队成员的名字和小队编号
                local name, _, subgroup = GetRaidRosterInfo(i)
                if name and subgroup then
                    -- 如果该小队还没有成员信息表，则创建一个新的表
                    if not teamInfo[subgroup] then
                        teamInfo[subgroup] = {}
                        teamInfo[subgroup]["list"] = {}
                        teamInfo[subgroup]["teamTotalAmount"] = 0
                        teamInfo[subgroup]["qiankuan"] = false
                        teamInfo[subgroup]["isMLGroup"] = false
                        teamInfo[subgroup]["mail"] = false
                    end
                    if ZL_CURRENT.playerBalance[name] and ZL_CURRENT.playerBalance[name]["balance"] < 0 then
                        --有欠款，则从工资里面扣除
                        amount = averageamount + ZL_CURRENT.playerBalance[name]["balance"]
                        teamInfo[subgroup]["teamTotalAmount"] = teamInfo[subgroup]["teamTotalAmount"] + amount
                        amount = amount .. "(已扣除欠款：" .. -ZL_CURRENT.playerBalance[name]["balance"] .. ")"
                        teamInfo[subgroup]["qiankuan"] = true
                    else
                        amount = averageamount
                        teamInfo[subgroup]["teamTotalAmount"] = teamInfo[subgroup]["teamTotalAmount"] + amount
                    end
                    for _, mailname in ipairs(ZL_CURRENT.mailPlayers) do
                        if mailname == name then
                            amount = amount .. "(邮寄)"
                            teamInfo[subgroup]["mail"] = true
                            break
                        end
                    end
                    if PlayerIsML(name) then
                        teamInfo[subgroup]["isMLGroup"] = true
                    end
                    -- 将成员名字,工资加入对应小队的表中
                    table.insert(teamInfo[subgroup]["list"], {name=name, amount=amount})
                end
            end
            for i = 1, 8 do
                if teamInfo[i] then
                    if teamInfo[i]["qiankuan"] or teamInfo[i]["mail"] then
                        --小队有人欠款或需要邮寄工资则通知每个人的工资
                        if teamInfo[i]["isMLGroup"] then
                            msgStr = ("第%d队[★]：%d人，工资：%d，"):format(i, #teamInfo[i]["list"], teamInfo[i]["teamTotalAmount"])
                        else
                            msgStr = ("第%d队：%d人，工资：%d，"):format(i, #teamInfo[i]["list"], teamInfo[i]["teamTotalAmount"])
                        end
                        table.insert(msglist, msgStr)
                        for _, data in ipairs(teamInfo[i]["list"]) do
                            -- if ZL_CURRENT.playerBalance[data.name] and ZL_CURRENT.playerBalance[data.name]["balance"] < 0 then
                            --     msgStr = data.name .. "：" .. data.amount .. "(已扣除欠款：" .. -ZL_CURRENT.playerBalance[data.name]["balance"] .. ")"
                            -- else
                            --     msgStr = data.name .. "：" .. data.amount
                            -- end
                            msgStr = data.name .. "：" .. data.amount
                            table.insert(msglist, msgStr)
                        end
                    else
                        if teamInfo[i]["isMLGroup"] then
                            msgStr = ("第%d队[★]：%d人，工资：%d，每人%d"):format(i, #teamInfo[i]["list"], teamInfo[i]["teamTotalAmount"], averageamount)
                        else
                            msgStr = ("第%d队：%d人，工资：%d，每人%d"):format(i, #teamInfo[i]["list"], teamInfo[i]["teamTotalAmount"], averageamount)
                        end
                        table.insert(msglist, msgStr)
                    end
                end
            end
            AuctionRecordFrame.playerBalanceFrame:Update()
        else
            msgStr = "当前没有收支记录！"
            table.insert(msglist, msgStr)
        end
        local index = 1
        local function sendMessage()
            if index <= #msglist then
                SendChatMessage(msglist[index], "RAID")
                -- print(msglist[index])
                index = index + 1
                C_Timer.After(0.3, sendMessage)
            end
        end
        sendMessage()
    end)
    currentIncomeFrame.RankingBtn = CreateButton(nil, currentIncomeFrame, "排名", "LEFT", SendMsgBtn, "RIGHT", 0, 0, 40)
    currentIncomeFrame.RankingBtn:SetScript("OnClick", function ()
        if ZL_CURRENT.playerBalance and next(ZL_CURRENT.playerBalance, nil) then
            local msgStr = ""
            local msglist = {}
            local tempList = {}
            for name, value in pairs(ZL_CURRENT.playerBalance) do
                table.insert(tempList, {name=name, totalAmount=value.totalAmount})
            end
            if #tempList > 1 then
                table.sort(tempList, function (a, b)
                    return a.totalAmount > b.totalAmount
                end)
            end
            table.insert(msglist, "<<<消费排名>>>")
            for index, data in ipairs(tempList) do
                msgStr = index .. "、" .. data.name .. "：" .. data.totalAmount
                table.insert(msglist, msgStr)
            end
            local index = 1
            local function sendMessage()
                if index <= #msglist then
                    SendChatMessage(msglist[index], "RAID")
                    index = index + 1
                    C_Timer.After(0.3, sendMessage)
                end
            end
            sendMessage()
        end
    end)
    currentIncomeFrame.RankingBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "LEFT", "RIGHT")
        if ZL_CURRENT.playerBalance and next(ZL_CURRENT.playerBalance, nil) then
            GameTooltip:AddLine("消费排名：")
            GameTooltip:AddDoubleLine("名字", "消费金额")
            local tempList = {}
            for name, value in pairs(ZL_CURRENT.playerBalance) do
                table.insert(tempList, {name=name, totalAmount=value.totalAmount})
            end
            if #tempList > 1 then
                table.sort(tempList, function (a, b)
                    return a.totalAmount > b.totalAmount
                end)
            end
            for index, data in ipairs(tempList) do
                if index <= 3 then
                    GameTooltip:AddDoubleLine(data.name, data.totalAmount, 1, 0, 0, 1, 0, 0)
                else
                    GameTooltip:AddDoubleLine(data.name, data.totalAmount, 1, 1, 1, 1, 1, 1)
                end
            end
        else
            GameTooltip:AddLine("暂时无人消费")
        end
        GameTooltip:Show()
    end)
    currentIncomeFrame.RankingBtn:SetScript("onLeave", function ()
        GameTooltip:Hide()
    end)
    currentIncomeFrame.totalIncomeFont = currentIncomeFrame:CreateFontString()
    local totalIncomeFont = currentIncomeFrame.totalIncomeFont
    totalIncomeFont:SetPoint("LEFT", currentIncomeFrame.RankingBtn, "RIGHT", 10, 0)
    totalIncomeFont:SetFont(GameFontNormal:GetFont(), 12)
    totalIncomeFont:SetTextColor(1, 1, 1)
    totalIncomeFont:SetText("浄收入：")
    totalIncomeFont:SetWordWrap(false)
    totalIncomeFont:SetJustifyH("LEFT")
    
    currentIncomeFrame.notesFont = currentIncomeFrame:CreateFontString()
    local notesFont = currentIncomeFrame.notesFont
    notesFont:SetPoint("TOPLEFT", groupNumbers, "BOTTOMLEFT", 5, -12)
    notesFont:SetFont(GameFontNormal:GetFont(), 12)
    notesFont:SetTextColor(1, 0.82, 0)
    notesFont:SetText("           名      称")
    notesFont:SetWordWrap(false)
    notesFont:SetJustifyH("LEFT")

    currentIncomeFrame.playerFont = currentIncomeFrame:CreateFontString()
    local playerFont = currentIncomeFrame.playerFont
    playerFont:SetPoint("LEFT", notesFont, "RIGHT", 45, 0)
    playerFont:SetFont(GameFontNormal:GetFont(), 12)
    playerFont:SetTextColor(1, 0.82, 0)
    playerFont:SetText("玩家名字")
    playerFont:SetWordWrap(false)
    playerFont:SetJustifyH("LEFT")

    currentIncomeFrame.amountFont = currentIncomeFrame:CreateFontString()
    local amountFont = currentIncomeFrame.amountFont
    amountFont:SetPoint("LEFT", playerFont, "RIGHT", 20, 0)
    amountFont:SetFont(GameFontNormal:GetFont(), 12)
    amountFont:SetTextColor(1, 0.82, 0)
    amountFont:SetText("收支金额(g)")
    amountFont:SetWordWrap(false)
    amountFont:SetJustifyH("LEFT")
    currentIncomeFrame:Hide()

    AuctionRecordFrame.playerBalanceFrame = CreateFrame("Frame", nil, AuctionRecordFrame)
    local playerBalanceFrame = AuctionRecordFrame.playerBalanceFrame
    playerBalanceFrame:SetPoint("TOPLEFT", AuctionRecordFrameDialogBG, "TOPLEFT")
    playerBalanceFrame:SetSize(AuctionRecordFrameDialogBG:GetWidth(), 50)
    playerBalanceFrame.SendMsgBtn = CreateButton(nil, playerBalanceFrame, "欠款通报", "TOPLEFT", playerBalanceFrame, "TOPLEFT", 5, -5)
    playerBalanceFrame.SendMsgBtn:SetScript("OnClick", function (self)
        if ZL_CURRENT.playerBalance and next(ZL_CURRENT.playerBalance, nil) then
            local msgStr = ""
            local count = 0
            local msglist = {}
            msgStr = "欠款通报："
            table.insert(msglist, msgStr)
            for name, data in pairs(ZL_CURRENT.playerBalance) do
                if data.balance < 0 and (not PlayerIsML(name)) then
                    msgStr = ("%s：%dg"):format(name, -data.balance)
                    table.insert(msglist, msgStr)
                    count = count + 1
                end
            end
            msgStr = "请以上欠款人员仔细核对，如有误，请及时提出！"
            table.insert(msglist, msgStr)
            local index = 1
            local function sendMessage()
                if index <= #msglist then
                    SendChatMessage(msglist[index], "RAID")
                    -- print(msglist[index])
                    index = index + 1
                    C_Timer.After(0.3, sendMessage)
                end
            end
            if count > 0 then
                sendMessage()
            else
                print(Prefix("当前没有欠款成员！"))
            end
        end
    end)
    playerBalanceFrame.mailConfirmBtn = CreateButton(nil, playerBalanceFrame, "邮寄确认", "LEFT", playerBalanceFrame.SendMsgBtn, "RIGHT")
    playerBalanceFrame.mailConfirmBtn:RegisterForClicks("LeftButtonUp", "RightButtonUp")
    playerBalanceFrame.mailConfirmBtn:SetScript("OnClick", function (self, button)
        if button == "LeftButton" then
            SendChatMessage("有需要邮寄的，【私聊】我发送：邮寄，插件自动登记，不要写错！", "RAID")
            SendChatMessage("有需要邮寄的，【私聊】我发送：邮寄，插件自动登记，不要写错！", "RAID")
            SendChatMessage("有需要邮寄的，【私聊】我发送：邮寄，插件自动登记，不要写错！", "RAID")
        elseif button == "RightButton" then
            if ZL_CURRENT.mailPlayers and (#ZL_CURRENT.mailPlayers > 0) and (not InCombatLockdown()) and (UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) then
                local index = 1
                local function changeGroup()
                    if index <= #ZL_CURRENT.mailPlayers then
                        local sender = ZL_CURRENT.mailPlayers[index]
                        local senderIndex = nil
                        local subgroup = nil
                        for i = 1, GetNumGroupMembers() do
                            local name, _, _subgroup = GetRaidRosterInfo(i)
                            if name == sender then
                                senderIndex = i
                                subgroup = _subgroup
                                break
                            end
                        end
                        if senderIndex then
                            local currentRoster = GetCurrentRoster()
                            for i = 8, subgroup+1, -1 do
                                if subgroup == i then
                                    break
                                else
                                    if #currentRoster[i] < 5 then
                                        SetRaidSubgroup(senderIndex, i)
                                        break
                                    else
                                        for j = 1, #currentRoster[i] do
                                            local name = currentRoster[i][j]
                                            if (not IsNeedMail(name)) then
                                                for k = 1, GetNumGroupMembers() do
                                                    local _name = GetRaidRosterInfo(k)
                                                    if _name == name then
                                                        SwapRaidSubgroup(senderIndex, k)
                                                        break
                                                    end
                                                end
                                            end
                                        end
                                    end
                                end
                            end
                            index = index + 1
                            C_Timer.After(0.3, changeGroup)
                        else
                            index = index + 1
                            C_Timer.After(0.001, changeGroup)
                        end
                    end
                end
                changeGroup()
            end
        end
    end)
    playerBalanceFrame.mailConfirmBtn:SetScript("OnEnter", function (self)
        GameTooltipShow(self, "LEFT", "RIGHT")
        if ZL_CURRENT.mailPlayers and #ZL_CURRENT.mailPlayers > 0 then
            GameTooltip:AddLine("邮寄名单：")
            GameTooltip:AddDoubleLine("名字", "小队")
            for _, name in ipairs(ZL_CURRENT.mailPlayers) do
                local isExist = false
                for i = 1, GetNumGroupMembers() do
                    local _name, _, subgroup = GetRaidRosterInfo(i)
                    if _name == name then
                        GameTooltip:AddDoubleLine(name, subgroup .. "队", 1, 1, 1, 1, 1, 1)
                        isExist = true
                        break
                    end
                end
                if (not isExist) then
                    GameTooltip:AddDoubleLine(name, "已离队", 1, 1, 1, 1, 0, 0)
                end
            end
        else
            GameTooltip:AddLine("没有需要邮寄工资的成员！")
        end
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine("左键点击：发送需要邮寄的信息")
        GameTooltip:AddLine("右键点击：将需要邮寄的成员调到后面的小队")
        GameTooltip:Show()
    end)
    playerBalanceFrame.mailConfirmBtn:SetScript("OnLeave", function ()
        GameTooltip:Hide()
    end)
    playerBalanceFrame.notesFont = playerBalanceFrame:CreateFontString()
    playerBalanceFrame.notesFont:SetPoint("LEFT", playerBalanceFrame.mailConfirmBtn, "RIGHT", 15, 0)
    playerBalanceFrame.notesFont:SetFont(GameFontNormal:GetFont(), 12)
    playerBalanceFrame.notesFont:SetTextColor(1, 1, 1)
    playerBalanceFrame.notesFont:SetText("|cffffd100负数|r：代表欠款金额")
    playerBalanceFrame.notesFont:SetWordWrap(false)
    playerBalanceFrame.notesFont:SetJustifyH("CENTER")
    playerBalanceFrame.playerNameFont = playerBalanceFrame:CreateFontString()
    local playerNameFont = playerBalanceFrame.playerNameFont
    playerNameFont:SetPoint("TOPLEFT", playerBalanceFrame.SendMsgBtn, "BOTTOMLEFT", 32, -5)
    playerNameFont:SetFont(GameFontNormal:GetFont(), 12)
    playerNameFont:SetTextColor(1, 0.82, 0)
    playerNameFont:SetText("玩家名字")
    playerNameFont:SetWordWrap(false)
    playerNameFont:SetJustifyH("CENTER")
    playerBalanceFrame.playerBalanceFont = playerBalanceFrame:CreateFontString()
    local playerBalanceFont = playerBalanceFrame.playerBalanceFont
    playerBalanceFont:SetPoint("LEFT", playerNameFont, "RIGHT", 55, 0)
    playerBalanceFont:SetFont(GameFontNormal:GetFont(), 12)
    playerBalanceFont:SetTextColor(1, 0.82, 0)
    playerBalanceFont:SetText("结余(g)")
    playerBalanceFont:SetWordWrap(false)
    playerBalanceFont:SetJustifyH("CENTER")

    playerBalanceFrame:Hide()

    --创建滚动条
    AuctionRecordFrame.scrollFrame = CreateFrame("ScrollFrame", nil, AuctionRecordFrame, "UIPanelScrollFrameTemplate")
    AuctionRecordFrame.scrollFrame:SetPoint("TOPLEFT", _G["AuctionRecordFrameDialogBG"], "TOPLEFT", 3, -50)
    AuctionRecordFrame.scrollFrame:SetPoint("BOTTOMRIGHT", _G["AuctionRecordFrameDialogBG"], "BOTTOMRIGHT", -3, 4)
    AuctionRecordFrame.scrollFrame:SetClipsChildren(true) --必须设置为true，scrollFrame所有的子元素才会被剪切
    AuctionRecordFrame.scrollFrame:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel) --重设滑动条鼠标滚轮事件
    --重设ScrollBar位置，放置到scrollFrame内，防止被剪切掉
    AuctionRecordFrame.scrollFrame.ScrollBar:ClearAllPoints()
    AuctionRecordFrame.scrollFrame.ScrollBar:SetPoint("TOPLEFT", AuctionRecordFrame.scrollFrame, "TOPRIGHT", -10, -15)
    AuctionRecordFrame.scrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", AuctionRecordFrame.scrollFrame, "BOTTOMRIGHT", -5, 15)

    local function Tab_OnClick(self)
        local frame = self:GetParent()
        local tabId = self:GetID()
        if tabId == 1 then
            historyFrame:Show()
            currentIncomeFrame:Hide()
            playerBalanceFrame:Hide()
        elseif tabId == 2 then
            historyFrame:Hide()
            currentIncomeFrame:Show()
            playerBalanceFrame:Hide()
        elseif tabId == 3 then
            historyFrame:Hide()
            currentIncomeFrame:Hide()
            playerBalanceFrame:Show()
        end
        PanelTemplates_SetTab(frame, tabId)
        local scrollchild = frame.scrollFrame:GetScrollChild()
        if scrollchild then
            scrollchild:Hide()
        end
        frame.scrollFrame:SetScrollChild(self.content)
        self.content:Show()
    end

    local function CreateTab(frame, numTabs, ...)
        frame.numTabs = numTabs
        local contents = {}
        local frameName = frame:GetName()
        local template = ""
        for i = 1, numTabs do
            if WOW_PROJECT_ID == 1 then
                template = "PanelTabButtonTemplate"
            elseif WOW_PROJECT_ID == 11 then
                template = "CharacterFrameTabButtonTemplate"
            end
            local tab = CreateFrame("Button", frameName.."Tab"..i, frame, template)
            tab:SetID(i)
            tab:SetText(select(i, ...))
            tab:SetScript("OnClick", Tab_OnClick)
            if WOW_PROJECT_ID == 1 then
                if i ==1 then
                    tab:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 5, 7)
                else
                    tab:SetPoint("TOPLEFT", _G[frameName.."Tab"..(i-1)], "TOPRIGHT", 1, 0)
                end
            elseif WOW_PROJECT_ID == 11 then
                if i ==1 then
                    tab:SetPoint("TOPLEFT", frame, "BOTTOMLEFT", 0, 5)
                else
                    tab:SetPoint("TOPLEFT", _G[frameName.."Tab"..(i-1)], "TOPRIGHT", -20, 0)
                end
            end
            tab.content = CreateFrame("Frame", nil, frame.scrollFrame)
            tab.content:SetPoint("TOPLEFT", frame.scrollFrame, "TOPLEFT")
            tab.content:SetSize(frame.scrollFrame:GetWidth() - 40, 600)
            tab.content:Hide()
            table.insert(contents, tab.content)
        end
        Tab_OnClick(_G[frameName.."Tab1"])
        return unpack(contents)
    end

    local historyContent, currentIncomeContent, playerBalanceContent = CreateTab(AuctionRecordFrame, 3, "历史", "当前", "结余")
    
    historyFrame.entries = setmetatable({}, {
        __index = function(t, v)
            local f = CreateFrame("Frame", nil, historyContent)
            if v > 1 then
                f:SetPoint("TOPLEFT", t[v - 1], "BOTTOMLEFT", 0, -8)
                f:SetPoint("TOPRIGHT", t[v - 1], "BOTTOMRIGHT", 0, -8)
            else
                f:SetPoint("TOPLEFT", historyContent, "TOPLEFT", 0, -5)
                f:SetPoint("TOPRIGHT", historyContent, "TOPRIGHT", 0, -5)
            end
            f:SetHeight(15)

            f.nameEditBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.nameEditBox:SetPoint("LEFT", f, "LEFT", 5, -5)
            f.nameEditBox:SetSize(80, 15)
            f.nameEditBox:SetFont(GameFontNormal:GetFont(), 10, "")
            f.nameEditBox:SetMultiLine(false)
            f.nameEditBox:SetTextColor(1, 1, 1)
            f.nameEditBox:SetJustifyH("LEFT")
            f.nameEditBox:SetAutoFocus(false)
            f.nameEditBox:Disable()

            f.totalIncomeBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.totalIncomeBox:SetPoint("LEFT", f.nameEditBox, "RIGHT", 9, 0)
            f.totalIncomeBox:SetSize(40, 15)
            f.totalIncomeBox:SetFont(GameFontNormal:GetFont(), 10, "")
            f.totalIncomeBox:SetMultiLine(false)
            f.totalIncomeBox:SetTextColor(1, 1, 1)
            f.totalIncomeBox:SetJustifyH("RIGHT")
            f.totalIncomeBox:SetAutoFocus(false)
            f.totalIncomeBox:SetNumeric(true)
            f.totalIncomeBox:SetTextInsets(0, 2, 0, 0)
            f.totalIncomeBox:Disable()

            f.auctiondateBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.auctiondateBox:SetPoint("LEFT", f.totalIncomeBox, "RIGHT", 9, 0)
            f.auctiondateBox:SetSize(105, 15)
            f.auctiondateBox:SetFont(GameFontNormal:GetFont(), 10, "")
            f.auctiondateBox:SetMultiLine(false)
            f.auctiondateBox:SetTextColor(1, 1, 1)
            f.auctiondateBox:SetJustifyH("RIGHT")
            f.auctiondateBox:SetAutoFocus(false)
            f.auctiondateBox:SetTextInsets(0, 2, 0, 0)
            f.auctiondateBox:Disable()

            f.del = CreateButton(nil, f, "-", "LEFT", f.auctiondateBox, "RIGHT", 2, 0, 20, 20)
            f.del:SetScript("OnClick", function (self)
                table.remove(ZL_HISTORY, v)
                historyFrame:Update()
            end)
            f.del:SetScript("OnEnter", function (self)
                GameTooltipShow(self, "LEFT", "RIGHT")
                if (#ZL_HISTORY[v].IncomeList > 0) then
                    GameTooltip:AddLine("收支记录：")
                    GameTooltip:AddDoubleLine("名称", "玩家    ".. pad_left("金额", 20))
                    for _, data in ipairs(ZL_HISTORY[v].IncomeList) do
                        local itemId = string.match(data.notes, "|c........|Hitem:(%d+):")
                        local amount = ""
                        if data.amount > 0 then
                            amount = pad_left(tostring(data.amount), 9)
                        else
                            amount = pad_left(tostring(data.amount), 8)
                        end
                        if itemId then
                            GameTooltip:AddDoubleLine(
                                "|T" .. cGetItemIcon(data.notes) .. ":12|t " .. data.notes,
                                data.player .. "        " .. amount .. "|cffffd100g|r", 1, 1, 1, 1, 1, 1)
                        else
                            GameTooltip:AddDoubleLine(
                                "|T:12|t " .. data.notes,
                                data.player .. "        " .. amount .. "|cffffd100g|r", 1, 1, 1, 1, 1, 1)
                        end
                    end
                else
                    GameTooltip:AddLine("没有收支记录！")
                end
                GameTooltip:AddLine("\n点击可删除该条拍卖记录，并且无法恢复！")
                GameTooltip:Show()
            end)
            f.del:SetScript("OnLeave", function () GameTooltip:Hide() end)
            f.res = CreateButton(nil, f, "", "LEFT", f.del, "RIGHT", 0, 0, 20, 20)
            f.res:SetNormalTexture("Interface\\Buttons\\UI-RotationLeft-Button-Up")
            f.res:SetPushedTexture("Interface\\Buttons\\UI-RotationLeft-Button-Down")
            f.res:SetScript("OnClick", function ()
                if next(ZL_CURRENT, nil) then
                    local totalincome = 0
                    if ZL_CURRENT.IncomeList and #ZL_CURRENT.IncomeList > 0 then
                        for _, fdata in ipairs(ZL_CURRENT.IncomeList) do
                            totalincome = totalincome + fdata.amount
                        end
                    end
                    ZL_CURRENT.totalincome = totalincome
                    table.insert(ZL_HISTORY, ZL_CURRENT)
                    ZL_CURRENT = {}
                end
                ZL_CURRENT = ZL_HISTORY[v]
                table.remove(ZL_HISTORY, v)
                do
                    if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                        for num, _ in ipairs(ZL_CURRENT.auctionlist) do
                            local f = ZL.AuctionFrame.entries[num]
                            f:SetValues(num)
                        end
                    end
                end
                ZL.AuctionFrame:Update()
                historyFrame:Update()
                currentIncomeFrame:Update()
                playerBalanceFrame:Update()
            end)
            f.res:SetScript("OnEnter", function (self)
                GameTooltipShow(self, "LEFT", "RIGHT", 3, 0)
                GameTooltip:AddLine("恢复到当前拍卖清单")
                GameTooltip:AddLine("注意：之前的拍卖清单将被清空并转为历史清单！", 1, 1, 1)
                GameTooltip:Show()
            end)
            f.res:SetScript("OnLeave", function ()
                GameTooltip:Hide()
            end)
            function f:SetValues(name, totalincome, auctiondate)
                self.nameEditBox:SetText(name)
                self.totalIncomeBox:SetNumber(totalincome)
                self.auctiondateBox:SetText(auctiondate)
                -- local textwidth = math.floor(self.itemNameFont:GetStringWidth()) + 10
                -- if textwidth > 90 then
                --     self.itemNameFont:SetTextScale(92/textwidth)
                -- end
            end
            t[v] = f
            return f
        end
    })
    function historyFrame:Update()
        for _, f in ipairs(self.entries) do f:Hide() end
        if next(ZL_HISTORY, nil) then
            if #ZL_HISTORY > 1 then
                table.sort(ZL_HISTORY, function (a, b)
                    return a.auctiondate < b.auctiondate
                end)
            end
            for num, data in ipairs(ZL_HISTORY) do
                local f = self.entries[num]
                if PlayerIsML() then
                    f.res:Show()
                else
                    f.res:Hide()
                end
                f:Show()
                f:SetValues(data.name, data.totalincome, data.auctiondate)
            end
            historyContent:SetHeight(20 * #ZL_HISTORY - 5)
        else
            historyContent:SetHeight(5)
        end
    end
    
    currentIncomeFrame.entries = setmetatable({}, {
        __index = function(t, v)
            local f = CreateFrame("Frame", nil, currentIncomeContent)
            if v > 1 then
                f:SetPoint("TOPLEFT", t[v - 1], "BOTTOMLEFT", 0, -8)
                f:SetPoint("TOPRIGHT", t[v - 1], "BOTTOMRIGHT", 0, -8)
            else
                f:SetPoint("TOPLEFT", currentIncomeContent, "TOPLEFT", 0, -5)
                f:SetPoint("TOPRIGHT", currentIncomeContent, "TOPRIGHT", 0, -5)
            end
            f:SetHeight(15)

            f.itemicon = CreateFrame("Button", nil, f)
            f.itemicon:SetSize(18, 18)
            f.itemicon:EnableMouse(true)
            f.itemicon:SetPoint("LEFT", f, "LEFT", 0, 0)
            f.itemicon:SetScript("OnEnter", function(self)
                local itemId = string.match(f.notes, "|c........|Hitem:(%d+):")
                if itemId then
                    GameTooltip:ClearAllPoints()
                    GameTooltip:ClearLines()
                    GameTooltip:SetOwner(self, "ANCHOR_NONE")
                    GameTooltip:SetHyperlink(f.notes)
                    GameTooltip:SetPoint("RIGHT", f, "LEFT", -5, 0)
                    GameTooltip:Show()
                end
            end)
            f.itemicon:SetScript("OnLeave", function() GameTooltip:Hide() end)

            f.notesbox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.notesbox:SetPoint("LEFT", f.itemicon, "RIGHT", 5, 0)
            f.notesbox:SetSize(100, 15)
            f.notesbox:SetFont(GameFontNormal:GetFont(), 10, "")
            f.notesbox:SetMultiLine(false)
            f.notesbox:SetTextColor(1, 1, 1)
            f.notesbox:SetJustifyH("LEFT")
            f.notesbox:SetAutoFocus(false)
            f.notesbox:SetScript("OnEnterPressed", function (self)
                if (strlen(self:GetText()) > 0) then
                    if (self:GetText() ~= ZL_CURRENT.IncomeList[v].notes) then
                        ZL_CURRENT.IncomeList[v].notes = self:GetText()
                        -- currentIncomeFrame:Update()
                    end
                else
                    self:SetText(ZL_CURRENT.IncomeList[v].notes)
                end
                self:ClearFocus()
            end)
            f.notesbox:SetScript("OnMouseUp", function (self)
                if (select(1, GetCursorInfo())) == "item" then
                    self:SetText(select(3, GetCursorInfo()))
                    ClearCursor()
                end
            end)
            f.playerbox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.playerbox:SetPoint("LEFT", f.notesbox, "RIGHT", 10, 0)
            f.playerbox:SetSize(70, 15)
            f.playerbox:SetFont(GameFontNormal:GetFont(), 10, "")
            f.playerbox:SetMultiLine(false)
            f.playerbox:SetTextColor(1, 1, 1)
            f.playerbox:SetJustifyH("LEFT")
            f.playerbox:SetAutoFocus(false)
            f.playerbox:SetScript("OnEnterPressed", function (self)
                if (strlen(self:GetText()) > 0) then
                    if (self:GetText() ~= ZL_CURRENT.IncomeList[v].player) then
                        ZL_CURRENT.IncomeList[v].player = self:GetText()
                        -- currentIncomeFrame:Update()
                    end
                else
                    self:SetText(ZL_CURRENT.IncomeList[v].player)
                end
                self:ClearFocus()
            end)

            f.amountbox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.amountbox:SetPoint("LEFT", f.playerbox, "RIGHT", 10, 0)
            f.amountbox:SetSize(50, 15)
            f.amountbox:SetFont(GameFontNormal:GetFont(), 10, "")
            f.amountbox:SetMultiLine(false)
            f.amountbox:SetTextColor(1, 1, 1)
            f.amountbox:SetJustifyH("RIGHT")
            f.amountbox:SetAutoFocus(false)
            f.amountbox:SetNumeric(false)
            f.amountbox:SetTextInsets(0, 2, 0, 0)
            f.amountbox:SetScript("OnEnterPressed", function (self)
                if (strlen(self:GetText()) > 0) then
                    if (self:GetText() ~= tostring(ZL_CURRENT.IncomeList[v].amount)) then
                        ZL_CURRENT.IncomeList[v].amount = tonumber(self:GetText())
                        currentIncomeFrame:Update()
                    end
                else
                    self:SetText(ZL_CURRENT.IncomeList[v].amount)
                end
                self:ClearFocus()

            end)

            f.del = CreateButton(nil, f, "-", "LEFT", f.amountbox, "RIGHT", 2, 0, 24)
            f.del:SetScript("OnClick", function (self)
                local data = {
                    type = "删除拍卖记录",
                    index = v,
                }
                MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
            end)
            f.del:SetScript("OnEnter", function (self)
                GameTooltipShow(self, "LEFT", "RIGHT")
                GameTooltip:AddLine("注意：点击可删除，不可恢复！")
                GameTooltip:AddLine("如需修改，直接在文本框编辑后按Enter键", 1, 1, 1)
                GameTooltip:AddLine("如需填写物品名称，可直接鼠标拖动物品到名称文本框", 1, 1, 1)
                GameTooltip:Show()
            end)
            f.del:SetScript("OnLeave", function () GameTooltip:Hide() end)
            function f:SetValues(notes, player, amount)
                local itemId = string.match(notes, "|c........|Hitem:(%d+):")
                if itemId then
                    f.itemicon:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
                    self.itemicon:SetNormalTexture(cGetItemIcon(notes))
                end
                self.notesbox:SetText(notes)
                self.playerbox:SetText(player)
                self.amountbox:SetNumber(amount)
            end

            t[v] = f
            return f
        end
    })
    function currentIncomeFrame:Update()
        for _, f in ipairs(self.entries) do f:Hide() end
        if PlayerIsML() then
            currentIncomeFrame.SendMsgBtn:Show()
            currentIncomeFrame.groupNumbers:Show()
            currentIncomeFrame.groupNumbersEditBox:Show()
        else
            currentIncomeFrame.SendMsgBtn:Hide()
            currentIncomeFrame.groupNumbers:Hide()
            currentIncomeFrame.groupNumbersEditBox:Hide()
        end
        local totalamount = 0
        if ZL_CURRENT["IncomeList"] and (#ZL_CURRENT["IncomeList"] > 0) then
            for num, data in ipairs(ZL_CURRENT["IncomeList"]) do
                local f = self.entries[num]
                f:Show()
                if PlayerIsML() then
                    f.notesbox:Enable()
                    f.playerbox:Enable()
                    f.amountbox:Enable()
                    f.del:Show()
                else
                    f.notesbox:Disable()
                    f.playerbox:Disable()
                    f.amountbox:Disable()
                    f.del:Hide()
                end
                
                f:SetValues(data.notes, data.player, data.amount)
                f.notes = data.notes
                totalamount = totalamount + data.amount
            end
            currentIncomeContent:SetHeight(20 * #ZL_CURRENT["IncomeList"] - 5)
        else
            currentIncomeContent:SetHeight(5)
        end
        totalIncomeFont:SetText("浄收入：|cffffd100" .. totalamount .. "|rg")
    end

    playerBalanceFrame.entries = setmetatable({}, {
        __index = function(t, v)
            local f = CreateFrame("Frame", nil, playerBalanceContent)
            if v > 1 then
                f:SetPoint("TOPLEFT", t[v - 1], "BOTTOMLEFT", 0, -8)
                f:SetPoint("TOPRIGHT", t[v - 1], "BOTTOMRIGHT", 0, -8)
            else
                f:SetPoint("TOPLEFT", playerBalanceContent, "TOPLEFT", 0, -5)
                f:SetPoint("TOPRIGHT", playerBalanceContent, "TOPRIGHT", 25, -5)
            end
            f:SetHeight(15)
            f.nameEditBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.nameEditBox:SetPoint("LEFT", f, "LEFT", 5, 0)
            f.nameEditBox:SetSize(110, 15)
            f.nameEditBox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.nameEditBox:SetMultiLine(false)
            f.nameEditBox:SetTextColor(1, 1, 1)
            f.nameEditBox:SetJustifyH("CENTER")
            f.nameEditBox:SetAutoFocus(false)
            f.nameEditBox:SetNumeric(false)
            f.nameEditBox:Disable()

            f.balanceEditBox = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
            f.balanceEditBox:SetPoint("LEFT", f.nameEditBox, "RIGHT", 10, 0)
            f.balanceEditBox:SetSize(60, 15)
            f.balanceEditBox:SetFont(GameFontNormal:GetFont(), 12, "")
            f.balanceEditBox:SetMultiLine(false)
            f.balanceEditBox:SetTextColor(1, 1, 1)
            f.balanceEditBox:SetJustifyH("RIGHT")
            f.balanceEditBox:SetTextInsets(0, 3, 0, 0)
            f.balanceEditBox:SetAutoFocus(false)
            f.balanceEditBox:SetNumeric(false)
            f.balanceEditBox:Disable()

            f.add = CreateButton(nil, f, "+", "LEFT", f.balanceEditBox, "RIGHT", 2, 0, 20, 20)
            f.add:SetScript("OnClick", function (self)
                StaticPopup_Show("ZL_ADDTOPLAYER", f.nameEditBox:GetText()).data = f.nameEditBox:GetText()
            end)
            f.rem = CreateButton(nil, f, "-", "LEFT", f.add, "RIGHT", 0, 0, 20, 20)
            f.rem:SetScript("OnClick", function (self)
                StaticPopup_Show("ZL_REMFROMPLAYER", f.nameEditBox:GetText()).data = f.nameEditBox:GetText()
            end)
            f.trade = CreateButton(nil, f, "清单", "LEFT", f.rem, "RIGHT", 0, 0, 30, 20, 10)
            f.trade:SetScript("OnClick", function ()
                local name = f.nameEditBox:GetText()
                local name_table = ZL_CURRENT.playerBalance[name]
                if name_table then
                    local balance = name_table.balance
                    local msglist = {}
                    local msgStr = "您还有待交易装备："
                    if name_table.items and #name_table.items > 0 then
                        for _, data in ipairs(name_table.items) do
                            if (not data["isTraded"]) then
                                local itemId = tonumber(string.match(data.notes, "|c........|Hitem:(%d+):"))
                                if itemId then
                                    if strlen(msgStr) + strlen(data.notes) > 255 then
                                        table.insert(msglist, msgStr)
                                        msgStr = data.notes
                                    else
                                        msgStr = msgStr .. data.notes
                                    end
                                end
                            end
                        end
                    end
                    if balance < 0 then
                        if msgStr == "您还有待交易装备：" then
                            msgStr = "您还欠款：" .. -balance .. "g，请及时交易我支付，感谢配合"
                        else
                            local balanceStr = "您还欠款：" .. -balance .. "g，请及时交易我，感谢配合"
                            if strlen(msgStr) + strlen(balanceStr) + 1 > 255 then
                                table.insert(msglist, msgStr)
                                msgStr = balanceStr
                            else
                                msgStr = msgStr .. "，" .. balanceStr
                            end
                        end
                        table.insert(msglist, msgStr)
                    end
                    if #msglist > 0 then
                        local index = 1
                        local function sendMessage()
                            if index <= #msglist then
                                SendChatMessage(msglist[index], "WHISPER", nil, name)
                                index = index + 1
                                C_Timer.After(0.3, sendMessage)
                            end
                        end
                        sendMessage()
                    else
                        print(Prefix("没有欠款和需要交易的物品！"))
                    end
                end
            end)
            f.trade:SetScript("OnEnter",function (self)
                GameTooltipShow(f, "LEFT", "RIGHT", 25)
                local name = f.nameEditBox:GetText()
                local name_table = ZL_CURRENT.playerBalance[name]
                if name_table and name_table.items and #name_table.items > 0 then
                    GameTooltip:AddLine("购买清单:")
                    GameTooltip:AddDoubleLine("名称", "是否已交易")
                    local items = name_table.items
                    for _, data in ipairs(items) do
                        if data.isTraded then
                            GameTooltip:AddDoubleLine(data["notes"], "是", 1, 1, 1, 1, 1, 1)
                        else
                            GameTooltip:AddDoubleLine(data["notes"], "否", 1, 1, 1, 1, 0, 0)
                        end
                    end
                    GameTooltip:AddLine(" ")
                    GameTooltip:AddLine(("总消费：%dg，欠款：%dg"):format(name_table.totalAmount, -name_table.balance))
                else
                    GameTooltip:AddLine("没有消费记录")
                end
                GameTooltip:Show()
            end)
            f.trade:SetScript("OnLeave", function ()
                GameTooltip:Hide()
            end)
            f.mail = CreateButton(nil, f, "邮寄", "LEFT", f.trade, "RIGHT", 0, 0, 30, 20, 10)
            f.mail:SetScript("OnClick", function (self)
                if (not MailFrame) or (not MailFrame:IsShown()) then
                    print(Prefix("先打开邮箱！"))
                    return
                end
                local targetName = f.nameEditBox:GetText()
                local moneyToMail = ZL_CURRENT.playerBalance[targetName]["balance"]
                if moneyToMail <= 0 then return end
                ClearSendMail()
                SetSendMailMoney(moneyToMail * 10000)
                SendMail(targetName, "<ZL>工资：" .. moneyToMail .. " g", "感谢您的付出，这是您的工资，请及时查收，期待您的下次加入！")
                ZL_CURRENT.playerBalance[targetName]["balance"] = 0
                playerBalanceFrame:Update()
            end)
            function f:SetValues(playerName, balanceAmount)
                self.nameEditBox:SetText(playerName)
                self.balanceEditBox:SetText(balanceAmount)
            end
            t[v] = f
            return f
        end
    })
    function playerBalanceFrame:Update()
        for _, f in ipairs(self.entries) do f:Hide() end
        local index = 1
        if ZL_CURRENT["playerBalance"] and next(ZL_CURRENT["playerBalance"], nil) then
            --如果在交易中则结余窗口第一个显示交易对象的记录
            if ZL.isTrading and ZL.tradePartner and (ZL_CURRENT["playerBalance"][ZL.tradePartner]) then
                local f = self.entries[index]
                f:Show()
                f:SetValues(ZL.tradePartner, ZL_CURRENT["playerBalance"][ZL.tradePartner]["balance"])
                f.nameEditBox:SetTextColor(0.57, 0.45, 1)
                f.balanceEditBox:SetTextColor(0.57, 0.45, 1)
                f.mail:Disable()
                -- if ((not MailFrame) or (not MailFrame:IsShown())) or ZL_CURRENT["playerBalance"][ZL.tradePartner]["balance"] <= 0 then
                --     f.mail:Disable()
                -- else
                --     f.mail:Enable()
                -- end
                index = index + 1
            end
            for name, data in pairs(ZL_CURRENT["playerBalance"]) do
                if ((not ZL.isTrading) or (name ~= UnitName("NPC"))) then  --and (not PlayerIsML(name))  and (data.balance ~= 0) 
                    local f = self.entries[index]
                    f:Show()
                    local balanceAmount = 0
                    if ZL_CURRENT["mailPlayers"] and #ZL_CURRENT["mailPlayers"] > 0 and ZL_CURRENT["aveWages"] then
                        local isExist = false
                        for _, mailname in ipairs(ZL_CURRENT["mailPlayers"]) do
                            if mailname == name then
                                balanceAmount = data.balance + ZL_CURRENT["aveWages"]
                                isExist = true
                                break
                            end
                        end
                        if not isExist then
                            balanceAmount = data.balance
                        end
                    else
                        balanceAmount = data.balance
                    end
                    f:SetValues(name, balanceAmount)
                    if index == 1 then
                        f.nameEditBox:SetTextColor(1, 1, 1)
                        f.balanceEditBox:SetTextColor(1, 1, 1)
                    end
                    if IsNeedMail(name) and data.balance > 0 then
                        f.mail:Enable()
                    else
                        f.mail:Disable()
                    end
                    -- if (not MailFrame) or (not MailFrame:IsShown()) or (data.balance <= 0) or
                    --     ((not ZL_CURRENT["mailPlayers"]) or (not ZL_CURRENT["mailPlayers"][name])) then
                    --     f.mail:Disable()
                    -- else
                    --     f.mail:Enable()
                    -- end
                    index = index + 1
                end
            end
            playerBalanceContent:SetHeight(20 * (index-1) - 5)
        else
            playerBalanceContent:SetHeight(5)
        end
    end
end

--ZL主界面更新监控ML是否掉线，如掉线暂停所有正在拍卖的物品
function ZL:FrameUpdate()
    self:SetScript("OnUpdate", function (self)
        if ZL.MLname and ZL.MLname ~= "" and (not UnitIsConnected(ZL.MLname)) then
            if ZL_CURRENT["auctionlist"] and #ZL_CURRENT["auctionlist"] > 0 then
                for index, data in ipairs(ZL_CURRENT["auctionlist"]) do
                    if data.state == "auctioning" and (not data.isPaused) then
                        data["isPaused"] = true
                        data.isPausedLinshi = true
                        local f = ZL.AuctionFrame.entries[index]
                        f.Frame1.timer:Pause()
                        f.Frame1.statetext:SetText("ML已离线，拍卖暂停中...")
                        f.Frame1.bidbox:Disable()
                        f.Frame1.bidBtn:Disable()
                        f.Frame1.autobidBtn:Disable()
                    end
                end
            end
        else
            if ZL_CURRENT["auctionlist"] and #ZL_CURRENT["auctionlist"] > 0 then
                for index, data in ipairs(ZL_CURRENT["auctionlist"]) do
                    if data.state == "auctioning" and data.isPaused and data.isPausedLinshi then
                        data["isPaused"] = false
                        data.isPausedLinshi = false
                        local f = ZL.AuctionFrame.entries[index]
                        f.Frame1.timer:Resume()
                        f.Frame1.statetext:SetText("拍卖中...")
                        if f.maxAutoBid then
                            f.Frame1.bidbox:Disable()
                            f.Frame1.bidBtn:Disable()
                            f.Frame1.lgnoreBtn:Disable()
                        else
                            f.Frame1.bidbox:Enable()
                            f.Frame1.bidBtn:Enable()
                            f.Frame1.lgnoreBtn:Enable()
                        end
                        f.Frame1.autobidBtn:Enable()
                    end
                end
            end
        end
    end)
end